iOS Contacts Framework: How to fetch contacts by phone number

Tobias picture Tobias · Jan 17, 2016 · Viewed 7.1k times · Source

I have a custom User class which stores the phone number of the user.

class User {
  let phoneNumber: String
}

How do I get the corresponding contact from the users contact book?

I tried the following but it seems like this works just for the contacts name because I'm always getting nil:

let predicate = CNContact.predicateForContactsMatchingName(userInstance.phoneNumber)
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPhoneNumbersKey]

// Is already permitted
try! CNContactStore().unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch).first  // This returns nil

I've searched in the docs but I didn't find a proper solution.

Answer

xiaoming picture xiaoming · Jan 17, 2016
let contactStroe = CNContactStore()
        let keysToFetch = [
            CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
            CNContactEmailAddressesKey,
            CNContactPhoneNumbersKey,
            CNContactImageDataAvailableKey,
            CNContactThumbnailImageDataKey]
contactStroe.requestAccessForEntityType(.Contacts, completionHandler: { (granted, error) -> Void in
if granted {
                let predicate = CNContact.predicateForContactsInContainerWithIdentifier(contactStroe.defaultContainerIdentifier())
                var contacts: [CNContact]! = []
                do {
                    contacts = try contactStroe.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch)// [CNContact]
                }catch {

                }
for contact in contacts {
                    var phoneStr = ""
                    var nameStr = ""
                    var number: CNPhoneNumber!
                    if contact.phoneNumbers.count > 0 {
                        number = contact.phoneNumbers[0].value as! CNPhoneNumber
                        phoneStr = number.stringValue.stringByReplacingOccurrencesOfString("-", withString: "")
                    }
                    nameStr = contact.familyName + contact.givenName
                    if !nameStr.isEmpty && !phoneStr.isEmpty {
                        let friend = YFriendsModel()
                        friend.name = nameStr
                        friend.phone = phoneStr
                        self.friendArr.append(friend)
                    }

                }

        })

this is my way, you can have a test