2015-09-02 18 views
1

我想實現使用ios9,CNContacts框架在表視圖上獲取的所有聯繫人的搜索。我可以通過GivenName,FamilyName等進行搜索,但當用戶在搜索欄中輸入搜索查詢時,還需要搜索電話號碼和電子郵件。就像我們可以在ios9 Apple聯繫人中搜索電話號碼/電子郵件一樣。在CNContact對象的所有值上執行搜索

我知道,由於phonenumbers/emailsaddresses是元組數組,所以使用NSPredicate格式字符串不可能做到這一點。

回答

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

我相信這段代碼可以被優化;)我做到了快... 我測試了這個解決方案只用電子郵件,但它應該工作以及與電話號碼。這取決於你如何處理檢索到的值。這可能只是一種解決方法,但正如你所說的,你不能用NSPredicate來實現。

+1

這對我有用。重新優化,您不必設置fetch.keysToFetch。它已經由前面的陳述確定了。此外,您不需要將聯繫人投遞到CNContact,它已經是一個。而且,您可以使用尾部閉包來使代碼看起來更乾淨。 –

+0

是的你是對的,謝謝你的建議。當我將更新答案... –

+0

感謝您的答案。我也在等待蘋果的迴應。讓我們看看他們是否有一個優化的方式。 – AkhilS