【问题标题】:Swift iOS9 New Contacts Framework - How to retrieve only CNContact that has a valid email address?Swift iOS9 新联系人框架 - 如何仅检索具有有效电子邮件地址的 CNContact?
【发布时间】:2015-09-19 07:34:02
【问题描述】:

在iOS9最新的Contacts框架中,如何只检索具有有效email地址的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 swift contacts


    【解决方案1】:

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

    您不能编写自定义谓词来过滤联系人,正如文档所说: “请注意,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])) {
    

    【讨论】:

    • 如何将它与 CNContactPickerViewController 一起使用?是否可以?或者您是否必须创建一个新的视图控制器来选择您的联系人?
    • 可以看方法:CNContactPickerViewController的predicateForEnablingContact
    • @adreacipriani, fetchRequest:CNContactFetchRequest 有谓词变量,我们可以找到谓词的特定联系人,对吧?你能举个例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多