【问题标题】:Implement search on all values of CNContact object实现对 CNContact 对象的所有值的搜索
【发布时间】:2015-09-02 14:31:43
【问题描述】:

我想使用 ios9、CNContacts 框架对在表格视图上获取的所有联系人进行搜索。我可以搜索 GivenName、FamilyName 等,但是当用户在搜索栏中输入搜索查询时,我还想搜索电话号码和电子邮件。就像我们可以在 ios9 Apple 联系人中搜索电话号码/电子邮件一样。

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

【问题讨论】:

    标签: iphone swift2 ios9 uisearchcontroller


    【解决方案1】:

    这是你可以做的

    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)
            }
        }
    }
    

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

    【讨论】:

    • 这对我有用。重新优化,不用设置fetch.keysToFetch。它已经由前面的语句设置。此外,您不需要将联系人投射到 CNContact,它已经是一个。而且,您可以使用尾随闭包使代码看起来更简洁。
    • 是的,您是对的,感谢您的建议。到时候我会更新答案......
    • 感谢您的回答。我也在等待苹果的回应。让我们看看他们是否有优化的方式。
    • contactStoremyContacts 初始化为什么? @ArminScheithauer
    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多