1

I am building an app in Swift. I would like to make predicate using a phoneNumber (as String) and retrieve the name of that contact -if it exists- from the CNContactStore. I can make a name predicate fairly easily by :

let pred = CNContact.predicateForContactsMatchingName(name: String)

But is there a way to do the same for a PhoneNumber. I can of course fetch the entire CNContactStore, loop through it and retrieve the contact. But I was wondering if there was any better way.

Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22
Quentin Malgaud
  • 405
  • 6
  • 21
  • Is it possible to have duplicate(same) contact numbers for two different person ? – VRAwesome Nov 07 '15 at 11:11
  • this is something I did not think about. I guess the CNContactStore would give me more than one value then. – Quentin Malgaud Nov 07 '15 at 11:18
  • 1
    @VRAwesome yes it is, and very common too. Examples: Me, my wife, and two kids share all the same "Home" phone number (though each sports a different "Mobile" phone number). My contact and several dozen others - share the same "Work main" phone number (the company's main line). – Motti Shneor Jun 02 '19 at 07:56

2 Answers2

5

For anyone who sees this post. In iOS11, Apple introduced this new method to fetch contact with phone number. https://developer.apple.com/documentation/contacts/cncontact/3020511-predicateforcontacts

See: https://nshipster.com/ios-12/

iWill
  • 135
  • 1
  • 4
  • Now this should now bee the assigned chosen answer, with the addition of "before iOS SDK 11, you must iterate all contacts and filter for the phone numbers you're looking for" – Motti Shneor Jun 02 '19 at 07:59
  • There are a bunch of other similarly helpful predicates there too! – boxed Jan 14 '22 at 08:38
2

In short: you can't create a predicate to filter based on phone number. You have to pull all of the contacts and iterate. NOTE: For any given phone number, it 1) may not exist in contacts, or 2) exist more than once.

Check out this post: https://forums.developer.apple.com/thread/19329

David Vernon
  • 286
  • 4
  • 9