How to retrieve all contacts using CNContact.predicateForContacts?
Asked Answered
H

1

6

So I have this code which works fine, but only if you have specified a name in the predicateForContacts parameter.

func retrieveContactsWithStore(store: CNContactStore) {
    do {
           let predicate = CNContact.predicateForContacts(matchingName: "John")
           let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]

           let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
           self.objects = contacts
           DispatchQueue.main.async(execute: { () -> Void in
               self.myTableView.reloadData()
           })
       } catch {
           print(error)
       }
}

I'd like to retrieve all the names of the people listed on address book.

Horrified answered 24/12, 2016 at 1:53 Comment(1)
Read the docs! developer.apple.com/reference/contacts/cncontactstore/… Note the sentence starting with: "To fetch all contacts..."Alfano
A
16

I'd like to retrieve all the names of the people listed on address book.

Form a CNContactFetchRequest specifying that the keys you want are names, and call enumerateContacts(with:usingBlock:).

    let req = CNContactFetchRequest(keysToFetch: [
        CNContactFamilyNameKey as CNKeyDescriptor,
        CNContactGivenNameKey as CNKeyDescriptor
    ])
    try! CNContactStore().enumerateContacts(with: req) {
        contact, stop in
        print(contact) // in real life, probably populate an array
    }
Alfano answered 24/12, 2016 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.