Member-only story

Accessing contacts in iOS

Mr.Javed Multani
1 min readOct 5, 2020

--

Applying 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

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet