2017-04-14 43 views
0

我想搜索聯繫人。我能夠從'包含'搜索匹配字符串的聯繫人。但我想搜索聯繫人,根據給定的搜索字符串開始。我的代碼看起來像那樣..按照給定的字符串從開頭搜索聯繫人

extension ContactViewController : UITextFieldDelegate { 

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

     let searchString = (textField.text! as NSString).replacingCharacters(in: range, with: string) 

     if searchString == "" 
     { 
      contacts = allContacts 
     } 
     else 
     { 
      do { 
       let predicate: NSPredicate = CNContact.predicateForContacts(matchingName: searchString) 
       let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), 
        CNContactImageDataKey,CNContactPhoneNumbersKey,CNContactImageDataAvailableKey] as [Any] 
       self.contacts = try self.contactStore.unifiedContacts(matching: predicate, keysToFetch:keys as! [CNKeyDescriptor]) 

      } 
      catch { 
       print("Unable to refetch the selected contact.") 
      } 
     } 

     //contacts = filterContactArray(contact: contacts) 
     self.tableContact.reloadData() 
     return true 
    } 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     textField.resignFirstResponder() 
     return true 
    } 
} 

所以請幫我解決這個問題。提前致謝。

+0

你面臨什麼問題? – KKRocks

回答

0

下面是使用謂詞與CNContact的解決方案。

let predicates = NSPredicate(format: CNContactGivenNameKey + " BEGINSWITH[cd] %@", searchString) 
       contacts = (allContacts as NSArray).filtered(using: predicates) as! [CNContact] 
       tableContact.reloadData()