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

标签 ios swift contacts

在最新的 iOS9 Contacts 框架中,如何只检索具有有效电子邮件地址的 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 ) 可用于按电子邮件地址过滤联系人!

您不能编写自定义谓词来过滤联系人,如文档所述: “请注意,联系人框架不支持通用谓词和复合谓词”

但是你当然可以“手动”完成,我给你看一个使用快速枚举的例子:

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

关于ios - Swift iOS9 新联系人框架 - 如何仅检索具有有效电子邮件地址的 CNContact?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665605/

相关文章:

Android 2.0 如何获取联系人组中的显示名称和号码

iphone - 正确继承 EKEvent 类

android - 如何在SourceTree中自动创建标签

ios - 具有多个自定义单元格类型的 RxSwift TableView

swift - AVAudioplayer 没有在 viewDidAppear 上重置

android - java.lang.IllegalArgumentException : Invalid column data1 in onActivityResult()

ios - 通用布局与不同的 iphone/ipad Storyboard

ios - 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?

ios - 关闭时将值传递给 View Controller 时出错 | swift 5

ios - 确定 ABContactsHelper 的 iOS 排序顺序