0

I want to search contact. I was able to search contact with matching string from 'contains'. But I want to search contact which start as per given searching string. My code is look like that..

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

So please help me to solve this problem. Thanks in advance.

NiravS
  • 1,144
  • 1
  • 12
  • 24

1 Answers1

0

Here is the solution to use predicates with CNContact.

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