2016-12-24 36 views
3

所以我有这个代码工作正常,但只有在predicateForContacts参数中指定了一个名称。如何使用CNContact.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) 
     } 
} 

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

+2

阅读文档! https://developer.apple.com/reference/contacts/cncontactstore/1403266-unifiedcontacts请注意以下句子:“要获取所有联系人...” – matt

回答

10

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

形成一个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 
    } 
相关问题