iOS 9 Swift Programming Cookbook (2015)
Chapter 4. Contacts
4.8 Displaying Contacts with Prebuilt System UI
Problem
You want to use a built-in system UI to display an existing contact’s information.
Solution
Use the forContact initializer of the CNContactViewController class and pass this method an instance of the CNContact that you want to display.
Discussion
Sometimes, you might want to display information for a particular contact but don’t want to write the whole UI yourself. Why would you? It’s a lot of work to display all the information. That’s where you can use the CNContactViewController class again.
NOTE
In this example, I am going to use my custom firstUnifiedContactMatchingName(_:toFetch:output:) method to fetch an existing contact. You don’t have to know the implementation of this method as you have learnt how to Recipe 4.2
So this is what we are going to do: we fetch a contact whose name matches “John” and display his information on the screen. Make sure that you fetch all the required keys for your contact. Otherwise, the controller won’t be able to display the contact’s information. You can get the list of reqiured keys by calling the descriptorForRequiredKeys() class function of the CNContactViewController.
let toFetch = [CNContactViewController.descriptorForRequiredKeys()]
store.firstUnifiedContactMatchingName("john", toFetch: toFetch){
guard let contact = $0 else{
print("No contact was found")
return
}
let controller = CNContactViewController(forContact: contact)
controller.contactStore = self.store
controller.allowsEditing = false
controller.displayedPropertyKeys =
[CNContactEmailAddressesKey, CNContactPostalAddressesKey]
self.navigationController?
.pushViewController(controller, animated: true)
}
By default, when a contact is displayed, the contact controller allows the user to edit that contact. You can disable that behavior by setting the allowsEditing property of the controller to false. Also bear in mind that you have to set the contactStore property of the controller to the same store from where you fetched your contact.
There is another interesting property on the controller: displayedPropertyKeys. As its name implies, it allows you to pass a series of contact property keys that have to be displayed. Other properties will be hidden. I have, in our code, enabled only email and postal addresses. The results are shown in Figure 4-10. Only the email and postal addresses requested to be displayed. Some other information such as full name are shown by default.
Figure 4-10. Displaying a contact
See Also