所以我有这个代码可以正常工作,但前提是你在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)
}
}
我想检索通讯录中列出的所有人的姓名。
答案 0 :(得分:12)
我想检索通讯录中列出的所有人的姓名。
形成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
}