Interacting with a user's Contacts database used to be, shall we say, "less than ideal". The AddressBook framework was great for itβs time, but itβs a bit past it's prime these days.
Contacts and Contacts UI are two new frameworks in iOS 9 (and OS X + watchOS) that make integrating Contact data into your app a breeze.
Here's how easy it is to search a userβs contacts and present one for viewing:
func presentContactMatchingName(name: String) throws {
let predicate = CNContact.predicateForContactsMatchingName(name)
let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey]
let store = CNContactStore()
let contacts = try store.unifiedContactsMatchingPredicate(
predicate,
keysToFetch: keysToFetch
)
if let firstContact = contacts.first {
let viewController = CNContactViewController(forContact: firstContact)
viewController.contactStore = self.store
presentViewController(viewController, animated: true, completion: nil)
}
}
Also, Apple has officially deprecated AddressBook and AddressBookUI so now's the time to make the switch!