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

Akh*_*ilS 1 iphone uisearchcontroller ios9 swift2

我想使用ios9,CNContacts框架对在表视图上获取的所有联系人实施搜索.我可以搜索GivenName,FamilyName等,但是当用户在搜索栏中输入搜索查询时,也想搜索电话号码和电子邮件.正如我们可以在ios9 Apple联系人中搜索电话号码/电子邮件一样.

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

Arm*_*uer 5

这是你能做的

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我确信这个代码可以优化;)我只是快速完成了......我只用电子邮件测试了这个解决方案,但它应该与电话号码一样好用.由您对检索到的值执行的操作取决于您.这可能只是一种解决方法,但正如您所说,您不能使用NSPredicate来实现.