Listing contacts with the Contacts framework

Listing contacts with the Contacts framework

Learn how to fetch contact information with the Contacts framework.

The Contacts framework provides you with he tools necessary for listing, reading, and displaying contact information from the user’s virtual address book.

It does it through the CNContact class, which stores information about a contact, such as name, phone numbers, and addresses.

To fetch contacts from the address book, the first thing to do is define what type of information you need with the CNKeyDescriptor type. Here are some examples:

let keys: [CNKeyDescriptor] = [
    CNContactGivenNameKey as CNKeyDescriptor,
    CNContactFamilyNameKey as CNKeyDescriptor,
    CNContactPhoneNumbersKey as CNKeyDescriptor
]

With the keys in hand, define a fetch request with CNContactFetchRequest. It defines the options to use when fetching contacts.

let request = CNContactFetchRequest(keysToFetch: keys)

A request can also have a predicate object, which can be used for filtering the results.

With the request object in hand, you can use a CNContactStore object to enumerate the contacts with the enumerateContacts(with:usingBlock:) method. It uses the request data to fetch the contacts matching them. The results are served over the results block.

var result: [CNContact] = []

do {
    try store.enumerateContacts(with: request) { contact, _ in
        result.append(contact)
    }
} catch {
    result = []
}

Remember that to be able to fetch contact information from the user’s address book, you must authorize access. Check Getting started with the Contacts framework to understand how to do it.