6

所以我有这段代码可以正常工作,但前提是你在predicateForContacts参数中指定了一个名称。

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)
       }
}

我想检索地址簿上列出的所有人员的姓名。

4

1 回答 1

15

我想检索地址簿上列出的所有人员的姓名。

形成一个CNContactFetchRequest指定您想要的键是名称,然后调用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
    }
于 2016-12-24T02:36:40.767 回答