对 CNContact 对象的所有值实施搜索

Implement search on all values of CNContact object

我想使用 ios9、CNContacts 框架对 table 视图中获取的所有联系人进行搜索。我可以搜索 GivenName、FamilyName 等,但是当用户在搜索栏中输入搜索查询时,我也想搜索 phone 号码和电子邮件。就像我们可以在 ios9 Apple 通讯录中搜索 phone numbers/emails。

我知道,因为phonenumbers/emails地址是元组数组,所以使用 NSPredicate 格式字符串是不可能的。

这是你可以做的

func findAllEmails () {
    let fetch = CNContactFetchRequest(keysToFetch: [CNContactEmailAddressesKey])
    fetch.keysToFetch = [CNContactEmailAddressesKey] // Enter the keys for the values you want to fetch here
    fetch.unifyResults = true
    fetch.predicate = nil // Set this to nil will give you all Contacts
    do {
        _ = try contactStore.enumerateContactsWithFetchRequest(fetch, usingBlock: {
            contact, cursor in
            // Do something with the result...for example put it in an array of CNContacts as shown below
            let theContact = contact as CNContact

            self.myContacts.append(theContact)

        })

    } catch {
        print("Error")
    }

    self.readContacts() // Run the function to do something with the values
}

func readContacts () {
    print(myContacts.count)
    for el in myContacts {
        for ele in el.emailAddresses {
          // At this point you have only the email Addresses from all your contacts - now you can do your search, put it in an TableView or whatever you want to do.... 
            print(ele.value)
        }
    }
}

我确信这段代码可以优化 ;) 我只是做的很快... 我仅使用电子邮件测试了此解决方案,但它应该也适用于 Phone 数字。如何处理检索到的值取决于您。这可能只是一种解决方法,但正如您所说,您不能使用 NSPredicate 来做到这一点。