How to search contact by email address through SearchBar in swift 3?

Viewed 1589

I am fetching contacts from contacts framework in swift3 by following code

    func getContctFromContactBook(_ completion:  @escaping ContactsHandler) {

    if contactsStore == nil {
        //ContactStore is control for accessing the Contacts
        contactsStore = CNContactStore()
    }

    switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) {
    case CNAuthorizationStatus.denied, CNAuthorizationStatus.restricted:
        //User has denied the current app to access the contacts.

        let productName = Bundle.main.infoDictionary!["CFBundleName"]!

        let alert = UIAlertController(title: "Unable to access contacts", message: "\(productName) does not have access to contacts. Kindly enable it in privacy settings ", preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {  action in
        })
        alert.addAction(okAction)

    case CNAuthorizationStatus.notDetermined:
        //This case means the user is prompted for the first time for allowing contacts
        contactsStore?.requestAccess(for: CNEntityType.contacts, completionHandler: { (granted, error) -> Void in
            //At this point an alert is provided to the user to provide access to contacts. This will get invoked if a user responds to the alert
            if  (!granted ){
                DispatchQueue.main.async(execute: { () -> Void in
                })
            }
            else{
            }
        })
    case  CNAuthorizationStatus.authorized:
        //Authorization granted by user for this app.
        var contactsArray = [CNContact]()

        let contactFetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch as [CNKeyDescriptor])

        do {
            try contactsStore?.enumerateContacts(with: contactFetchRequest, usingBlock: { (contact, stop) -> Void in
                //Ordering contacts based on alphabets in firstname
                contactsArray.append(contact)
            })
            completion(contactsArray, nil)
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

I got all contacts by this code but my problem is that I have to search contact from search bar by email address using predicate. When I am searching by name I am getting results but I don't have any idea how to add predicate for email address. I am posting search logic below , Please any one suggest me the right way. Here's my search logic.

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if (searchText.characters.count > 0)
{
    let predicate: NSPredicate
    if searchText.characters.count > 0 {
        predicate = CNContact.predicateForContacts(matchingName: searchText)

    } else {
        predicate = CNContact.predicateForContactsInContainer(withIdentifier: contactsStore!.defaultContainerIdentifier())
    }
    let store = CNContactStore()
    do {

        filteredContacts = try store.unifiedContacts(matching: predicate,
                                                     keysToFetch: allowedContactKeys())
    }
    catch {
        print("Error!")
    }
}
else
{
    self.filteredContacts = self.contactsArray
}

 self.tblContact.reloadData()
 }

     func allowedContactKeys() -> [CNKeyDescriptor]{
      //We have to provide only the keys which we have to access. We  should avoid unnecessary keys when fetching the contact. Reducing the keys means faster the access.

    return [CNContactEmailAddressesKey as CNKeyDescriptor,
           CNContactNamePrefixKey as CNKeyDescriptor,
            CNContactGivenNameKey as CNKeyDescriptor,
            CNContactFamilyNameKey as CNKeyDescriptor,
            CNContactOrganizationNameKey as CNKeyDescriptor,
            CNContactBirthdayKey as CNKeyDescriptor,
            CNContactImageDataKey as CNKeyDescriptor,
            CNContactThumbnailImageDataKey as CNKeyDescriptor,
            CNContactImageDataAvailableKey as CNKeyDescriptor,
            CNContactPhoneNumbersKey as CNKeyDescriptor,
    ]
}
2 Answers

There's a better way :)

let predicate = CNContact.predicateForContacts(matchingEmailAddress: "some@example.com")
Related