How to retrieve all contacts using CNContact.predicateForContacts?

馋奶兔 提交于 2019-12-06 05:35:25

问题


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.


回答1:


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
    }


来源:https://stackoverflow.com/questions/41309643/how-to-retrieve-all-contacts-using-cncontact-predicateforcontacts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!