1

Hi I'm trying to filter my contact, all is well in the simulator xcode, but when I try it on my iPhone I have a problem with regular expression predicate. Any suggestions ?. Thank you very much.

func updateSearchResultsForSearchController(searchController: UISearchController) {

    self.filteredContacs.removeAll(keepCapacity: false)
        let searchPredcate = NSPredicate(format: "givenName contains[c] %@ OR familyName contains[c] %@",searchController.searchBar.text!)
    let array = (self.contacts as NSArray).filteredArrayUsingPredicate(searchPredcate)
    self.filteredContacs = array as! [CNContact]

    self.tableViewContacts.reloadData()

}

1 Answers1

1

You can use CNContact Predicates for that.

- (NSArray*)searchContactsMatchingName:(NSString*)pSearchName andKeysToFetch:(NSArray*)pKeysToFetch 
{
    NSError *pError = nil;
    NSPredicate *pPredicate    = [CNContact predicateForContactsMatchingName:pSearchName];
    CNContactStore *pStore     = [[CNContactStore alloc] init];
    NSArray *pResults          = [pStore unifiedContactsMatchingPredicate:pPredicate keysToFetch:pKeysToFetch error:&pError];

    return pResults;
}
Annie Dev
  • 282
  • 1
  • 10
  • Note, this will also return contacts that match organization name or nickname. If you want results for only first/last, then I found in https://stackoverflow.com/questions/32665605/swift-ios9-new-contacts-framework-how-to-retrieve-only-cncontact-that-has-a-va that the docs state: "_Note that generic and compound predicates are not supported by the Contacts framework._" So the only way to fetch contacts matching _only_ first/last name is to use this answer and then manually filter results afterwards – adam.wulf Aug 23 '19 at 19:53