這裏是你能做什麼
func findAllEmails() {
let fetch = CNContactFetchRequest(keysToFetch: [CNContactEmailAddressesKey])
fetch.keysToFetch = [CNContactEmailAddressesKey] // Enter the keys for the values you want to fetch here
fetch.unifyResults = true
fetch.predicate = nil // Set this to nil will give you all Contacts
do {
_ = try contactStore.enumerateContactsWithFetchRequest(fetch, usingBlock: {
contact, cursor in
// Do something with the result...for example put it in an array of CNContacts as shown below
let theContact = contact as CNContact
self.myContacts.append(theContact)
})
} catch {
print("Error")
}
self.readContacts() // Run the function to do something with the values
}
func readContacts() {
print(myContacts.count)
for el in myContacts {
for ele in el.emailAddresses {
// At this point you have only the email Addresses from all your contacts - now you can do your search, put it in an TableView or whatever you want to do....
print(ele.value)
}
}
}
我相信這段代碼可以被優化;)我做到了快... 我測試了這個解決方案只用電子郵件,但它應該工作以及與電話號碼。這取決於你如何處理檢索到的值。這可能只是一種解決方法,但正如你所說的,你不能用NSPredicate來實現。
這對我有用。重新優化,您不必設置fetch.keysToFetch。它已經由前面的陳述確定了。此外,您不需要將聯繫人投遞到CNContact,它已經是一個。而且,您可以使用尾部閉包來使代碼看起來更乾淨。 –
是的你是對的,謝謝你的建議。當我將更新答案... –
感謝您的答案。我也在等待蘋果的迴應。讓我們看看他們是否有一個優化的方式。 – AkhilS