Swift iOS9 新联系人框架 - 如何仅检索具有有效电子邮件地址的 CNContact?

Swift iOS9 New Contacts Framework - How to retrieve only CNContact that has a valid email address?

在 iOS9 的最新联系人框架中,如何仅检索具有有效电子邮件地址的 CNContact?

当前代码:

func getContacts() -> [CNContact] {
    let contactStore = CNContactStore()
    let predicate: NSPredicate = NSPredicate(format: "")
    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey]

    do {
        return try contactStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch)
    } catch {
        return []
    }
}

目前 (iOS 9.0) 似乎没有谓词 (see CNContact Predicates) 可用于按电子邮件地址过滤联系人!

您不能编写自定义谓词来过滤联系人,如文档所述: "Note that generic and compound predicates are not supported by the Contacts framework"

但是你当然可以做到"manually",我给你看一个使用快速枚举的例子:

let contactStore = CNContactStore()
fetchRequest.unifyResults = true //True should be the default option
do {
    try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey])) {
        (contact, cursor) -> Void in
        if (!contact.emailAddresses.isEmpty){
            //Add to your array
        }
    }
}
catch{
    print("Handle the error please")
}

:

在 Swift 的较新版本中,对 contactStore.enumerateContactsWithFetchRequest 的调用需要更新为:

try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey] as [CNKeyDescriptor])) {