本文介绍了Swift iOS9新联系人框架 - 如何仅检索具有有效电子邮件地址的CNContact?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the latest Contacts framework for iOS9, how to retrieve only CNContact that has a valid email address?

当前代码:

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)似乎没有谓词()可通过电子邮件地址过滤联系人!

For now (iOS 9.0) it seems that no predicates (see CNContact Predicates) are available to filter contacts by email address!

您无法编写自定义谓词来过滤联系人,因为文档说:
请注意,Contacts framewo不支持泛型谓词和复合谓词rk

You can't write a custom predicate to filter contacts, as the doc says: "Note that generic and compound predicates are not supported by the Contacts framework"

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

But of course you can do it "manually", I show you an example using fast enumeration:

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 iOS9新联系人框架 - 如何仅检索具有有效电子邮件地址的CNContact?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 15:31