Accessing Contacts
suggest changeApplying a filter
To access contacts, we should apply a filter of type NSPredicate
to our contactStore variable which we defined it in Authorizing Contact Access example. For example, here we want to sort out contacts with name matching with our own:
Swift
let predicate = CNContact.predicateForContactsMatchingName("Some Name")
Objective-C
NSPredicate *predicate = [CNContact predicateForContactsMatchingName:@"Some Name"];
Specifying keys to fetch
Here, we want to fetch the contact’s first name, last name and profile image:
Swift
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactImageDataKey]
Fetching contacts
Swift
do {
let contacts = try contactStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keys)
} catch let error as NSError {
//...
}
Accessing contact details
Swift
print(contacts[0].givenName)
print(contacts[1].familyName)
let image = contacts[2].imageData
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents