Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

swift 2 contacts framework

The first installment of a Swift Tutorial Series aimed at getting you upto speed with the contacts framework. Part one will cover What is the Contact Framework, Using the CNContactStore Class and the CNContact Object. I will show you how to create Contacts in Swift and add in extra information like birthdays, anniversaries, social media profiles and more.

Topics we cover in this tutorial

Swift Contact Framework

Firstly, What is a Framework in Swift Programming? Well, A framework is a huge collection of code that provides an architecture for developers to build their applications to fit in with the frameworks standards of use, Understand? A framework is like guidelines, help, code libraries all rolled into one.

So, What is the Contact Framework? Well, This is from Apple and they created the Contact Framework to replace the Address Book Framework and it provides an Objective-C or Swift API to access the user’s contact information. Since most apps only read contact information without making changes, this framework is optimized for thread-safe, read-only usage [1].

The Contacts Framework should be used by any developer who is wishing to access information to import, select, display, modify and save contact information on an iOS Device. The base of the contact framework gives us the CNContact object which represents a specific contact and it also gives us database access using the CNContactStore class.

CNContact

The CNContact class is like NSDictionary; it has a mutable subclass CNMutableContact you can use to modify contact properties. For contact properties that can have multiple values, such as phone numbers or email addresses, an array of CNLabeledValue objects is used.

Here is a representation of the CNContact Object, This image was created by Apple and remains their copyright:

CNContact Object Representation

Before you do anything in the Address Book you need to make sure that you have sufficient privileges to create a new contact or even fetch results. You do this by by using the class method in the contact store: authorizationStatusForEntityType(_:). This method takes one parameter of type: CNEntityType.

So, if you do not have access, you would use the Contact Store method requestAccessForEntityType(_:completionHandler:) to request access.

Contact objects for iOS are thread-safe. It is recommended that you fetch all our operations using a background thread. This way you can safely display your contacts on the view whilst accessing the same content object from the main thread.

Creating Contacts

Firstly, This Swift 2 Contact Framework Tutorial Series assumes that you have basic understanding of the Swift Programming Language and that are comfortable with creating a new Single View Application.

There is a great Introduction to Swift Programming to get you started if you need to.

Now I’m going to show you how to create contacts in your iOS application by inserting the new contact into the contacts database. We will do this by first checking that we have sufficient privileges by checking the authorizationStatusForEntityType(_:) and requesting access if we do not have it. Then we will create an instance of the class CNMutableContact and create a few properties such as givenName, middleName and familyName. There are quite a few others that I will show you too. I will then show you how to instantiate the CNSaveRequest and add the addContact(_:toContainerWithIdentifier:) method onto it. Finally, we will execute it onto our store using the executeSaveRequest(_:).

Does this seem a little scary? Don’t worry – I’m with you all the way, We will do this together.

Step 1: Basic Information

The first thing you need to do is create a New Single View Application. Once you have that project created and ready to go we are going to request access to the Contact Store.

At the top of your ViewController.swift file, we need to import the iOS 9 Contacts Framework, like so:


import ContactsUI

Next, we need to check if we have the correct privileges using: authorizationStatusForEntityType(_:), If we do we are then going to call a method that we will create called createContact():


switch CNContactStore.authorizationStatusForEntityType(.Contacts){
case .Authorized:
   createContact()
   // This is the method we will create
case .NotDetermined:
  store.requestAccessForEntityType(.Contacts){succeeded, err in
   guard err == nil && succeeded else{
     return
  }
  self.createContact()
 }
default:
  print("Not handled")
}

We now need to create a property on the class which will be an instance of the contact store:


var store = CNContactStore()

Now create the method createContact() that I mentioned earlier and add in some basic information such as name etc..


let contactData = CNMutableContact()
contactData.givenName = "Liam"
contactData.middleName = "G"
contactData.lastName = "Gallacgher"
contactData.nickname = "yaffaria"

Step 2: Add Photo

In your Xcode project, drag an image into your project navigation panel so that you can use it here for a dummy one. I have a basic one called contactface.png. I’m also going to show you how to add this code so that even if there is no image it will not crash your app. We do this by using a Swift If Statement. We say that, if the image exists then use it and add it to the contacts, otherwise just skip this code entirely. Its always better to think about possible ways that your app can crash before you make it live and to account for these potential errors.

Ok, so let’s assume that you also called your image contactface.png. This is the code you would use:


if let img = UIImage(named: "contactface"),
    let imgData = UIImagePNGRepresentation(img){
    contactData.imageData = imgData
}

Step 3: Add Phone Numbers

The way we add phone numbers is to first set an array of CNlabeledValue on the phoneNumbers property inside the Contact Object. Labeled values are just instances of this class and we can have both a label and a value. Where the label will be CNLabelHome or CNLabelWork and the value would be represented by CNPhoneNumber. We do this like so:


let homePhone = CNLabeledValue(label: CNLabelHome,value: CNPhoneNumber(stringValue: "305123123"))
let workPhone = CNLabeledValue(label: CNLabelWork, value: CNPhoneNumber(stringValue: "305123123"))

contactData.phoneNumbers = [homePhone, workPhone]

Step 4: Add Email Address

Just like when adding phone numbers, adding emails also takes an array CNlabeledValue, allowing us to add one for work and home. However, this time it does not take CNPhoneNumber, it takes a string value:


let homeEmail = CNLabeledValue(label: CNLabelHome, value: "[email protected]")
let workEmail = CNLabeledValue(label: CNLabelWork,value: "[email protected]")

contactData.emailAddresses = [homeEmail, workEmail]

Step 5: Add Job Role

Adding in job roles is rather easy, you only need to specify string values for jobTitle , organizationName & departmentName


contactData.jobTitle = "Bar Manager"
contactData.organizationName = "Best English Bar"
contactData.departmentName = "Food and Beverages"

Step 6: Add Social Profiles

We all love to be connected, well my daughter never gets off her phone… anyway, so, lets say you want to add social media information to your contacts in Core Data. I’m only going to show you how to add Twitter and Facebook information to the contact but the Contacts Framework has a ton you can use. Check out what has been added in the recent update of the Contacts Framework: Contacts Changes for Swift .

Now, to add Twitter and Facebook to Contacts you would use this code:


let facebookProfile = CNLabeledValue(label: "FaceBook", value:
CNSocialProfile(urlString: nil, username: "ios_blog",
userIdentifier: nil, service: CNSocialProfileServiceFacebook))

let twitterProfile = CNLabeledValue(label: "Twitter", value:
CNSocialProfile(urlString: nil, username: "ios_blog",
userIdentifier: nil, service: CNSocialProfileServiceTwitter))

contactData.socialProfiles = [facebookProfile, twitterProfile]

Step 7: Add Instant Messaging

To add in instant messaging information, like Skype and AIM you would set a value of the instantMessageAddresses property, which likes he rest of the properties we have coded takes an array of CNLabeledValue (of type: CNInstantMessageAddress). Just like the social media properties, these values take strings, like so:


let skypeAddress = CNLabeledValue(label: "Skype", value:
CNInstantMessageAddress(username: "ios_blog",
service: CNInstantMessageServiceSkype))

let aimAddress = CNLabeledValue(label: "AIM", value:
CNInstantMessageAddress(username: "ios_blog",
service: CNInstantMessageServiceAIM))

contactData.instantMessageAddresses = [skypeAddress, aimAddress]

Step 8: Add Birthday & Anniversary

It’s important to remember birthdays and anniversaries, otherwise you just might find yourself loosing friends and having an argument with the spouse. To add in birthday information you instantiate a constant with NSDateComponents and then add in the month, year and day values. Like so:


let birthday = NSDateComponents()
birthday.year = 1988
birthday.month = 12
birthday.day = 05
contactData.birthday = birthday

We also use NSDateComponents for anniversary but this time we use an array of CNLabeledValue objects. Also, do not set the year for the anniversary as it is an annual event:


let anniversaryDate = NSDateComponents()

anniversaryDate.month = 10
anniversaryDate.day = 12

let anniversary = CNLabeledValue(label: "Anniversary", value: anniversaryDate)

contactData.dates = [anniversary]

Step 9: Add Notes

Adding notes to your contacts object is very simple. You just use the note property and it takes a value of String:


contactData.note = "Extra Information For the Contact"

Step 10: Save to database

Finally, We gather all that data – which we have been assigning to contactData throughout and store it to the database:


let request = CNSaveRequest()
request.addContact(contactData, toContainerWithIdentifier: nil)

do{
   try storeo.executeSaveRequest(request)
   print("Successfully added the contact")
} catch let err{
   print("Failed to save the contact. \(err)")
}

A quick note, You can run this many times but it will add in a new item each time. You should probably perform some checks to see if the user is already present first.

Summary

In this Swift 2 Contacts Framework Tutorial you have gained an insight into the CNContactStore Class and the CNContact Object which information and representation on how these are modeled. I have shown you how to Create a Contact in Swift, Add basic information and delved into showing you what other type of contact information you can store in the Contacts Store.

Part 2

Part two is currently been written and will be available soon. Part two of the Swift 2 Contact Framework series will cover searching for contacts, how to update and delete items from the Contacts store and how to format contact data Join up to the mailing list and stay in the know.

Part two is now live, and its a corker, check it out Swift 2 Contacts Framework, Part 2

References

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

I work in the shadows. You can thank me by being a good soul.

Comments

comments