小编典典

Swift iOS9 New Contacts Framework-如何仅检索具有有效电子邮件地址的CNContact?

swift

在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 []
    }
}

阅读 333

收藏
2020-07-07

共1个答案

小编典典

目前(iOS
9.0),似乎没有谓词(请参阅CNContact谓词)可用于通过电子邮件地址过滤联系人!

您无法编写自定义谓词来过滤联系人,因为该文档说: “请注意,Contacts框架不支持通用谓词和复合谓词”

但是当然您可以“手动”完成操作,我为您展示了使用快速枚举的示例:

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])) {
2020-07-07