What is the correct way to set CNContact.predicateForContacts
to select the field "email" in CNContacts? Like in SQL where email like "%lbs%"
?
This is my function to delete a lot of imported contacts I want to get rid of. But the function return 0 hits. But there are more than 1000 contacts with "lbs" in the field email.
func deleteContacts(){
let store = CNContactStore()
let predicate = CNContact.predicateForContacts(matchingName: "lbs")
let toFetch = [CNContactEmailAddressesKey]
do{
let contacts = try store.unifiedContacts(matching: predicate,keysToFetch: toFetch as [CNKeyDescriptor])
guard contacts.count > 0
else{
print("No contacts found")
return
}
guard let contact = contacts.first else{
return
}
let req = CNSaveRequest()
let mutableContact = contact.mutableCopy() as! CNMutableContact
req.delete(mutableContact)
do{
try store.execute(req)
print("Success, deleted the data: Count: \(contacts.count)")
} catch let e{
print("Error = \(e)")
}
} catch let err{
print(err)
}
}
Your predicate is trying to find contacts where the person's name matches the string lbs
.
There is no built-in predicate for finding contacts that have an email address containing a specific string. The solution is to use enumerateContacts
and look at each individual contact's list of email addresses. You will then need to check to see if any of the contact's email address contains the string you wish to check.