How can I fetch a contact by phone number

I've been exploring with the `CNContactStore` and having problems figuring out how to fetch a contact by phone number.


Is guess I could use the NSPredicate somehow, but how would I write a predicate on phone numbers?

Answered by OOPer in 61032022

In the CNContactStore Class Reference, you can find this description:

- unifiedContactsMatchingPredicate:keysToFetch:error:

Use only the predicates from the

CNContact
class predicates. Compound predicates are not supported by this method.


And in the CNContact class reference, you can find only two predicate methods:

+ predicateForContactsMatchingName:

+ predicateForContactsWithIdentifiers:

(Other two predicate methods are for groups and containers.)


So, if you want to choose contacts by phone number, you need to retrieve all contacts and filter it programatically yourself.


You can use - enumerateContactsWithFetchRequest:error:usingBlock: to fetch all the contacts, but all the same,

Compound predicates are not supported. (in predicate of CNContactFetchRequest)

Accepted Answer

In the CNContactStore Class Reference, you can find this description:

- unifiedContactsMatchingPredicate:keysToFetch:error:

Use only the predicates from the

CNContact
class predicates. Compound predicates are not supported by this method.


And in the CNContact class reference, you can find only two predicate methods:

+ predicateForContactsMatchingName:

+ predicateForContactsWithIdentifiers:

(Other two predicate methods are for groups and containers.)


So, if you want to choose contacts by phone number, you need to retrieve all contacts and filter it programatically yourself.


You can use - enumerateContactsWithFetchRequest:error:usingBlock: to fetch all the contacts, but all the same,

Compound predicates are not supported. (in predicate of CNContactFetchRequest)

Actually, for since iOS 11 SDK CNContactStore provides a new pre-configured NSPredicate for exactly this:


+ (NSPredicate *)predicateForContactsMatchingPhoneNumber:(CNPhoneNumber *)phoneNumber;


https://developer.apple.com/documentation/contacts/cncontact/3020511-predicateforcontactsmatchingphon?language=objc

How can I fetch a contact by phone number
 
 
Q