2017-04-14 3 views
0

Ich möchte Kontakt suchen. Ich war in der Lage, Kontakt mit passender Zeichenfolge von "enthält" zu suchen. Aber ich möchte den Kontakt suchen, der wie der angegebene Suchstring beginnt. Mein Code sieht so aus ..Suche Kontakt nach vorgegebenen String von Anfang

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

Bitte helfen Sie mir, dieses Problem zu lösen. Danke im Voraus.

+0

Welches Problem haben Sie? – KKRocks

Antwort

0

Hier ist die Lösung, Prädikate mit CNContact zu verwenden.

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