Tobias
Tobias

Reputation: 4653

iOS Contacts Framework: How to fetch contacts by phone number

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.

Upvotes: 3

Views: 7687

Answers (3)

Andrea.Ferrando
Andrea.Ferrando

Reputation: 987

Swift 3 A nice solution, taking care also of efficiency:

    func getAllContacts() {
        let status = CNContactStore.authorizationStatus(for: CNEntityType.contacts) as CNAuthorizationStatus

        if status == CNAuthorizationStatus.denied {
            self.showAccessContactsDeniedAlert()
            return
        }
        let contactStore = CNContactStore()
        let keysToFetch = [
            CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
            CNContactEmailAddressesKey,
            CNContactPhoneNumbersKey,
            CNContactImageDataAvailableKey,
            CNContactThumbnailImageDataKey] as [Any]
        let request = CNContactFetchRequest(keysToFetch:keysToFetch as! [CNKeyDescriptor])
        do {
        try contactStore.enumerateContacts(with: request, usingBlock: { (contact:CNContact, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
            print(contact)
            for email in contact.emailAddresses {
                var dict = [String:String]()
                dict["name"] = contact.familyName + contact.givenName
                dict["email"] = email.value
                self.allContacts.add(dict)
            }
        })
        } catch {
            //catch
        }
    }

In this case I save name and email into a dict and I add it to a class variable called allContacts.

Note that a contact can have more than one email, so I create a dict for any email address in this case

Upvotes: 0

William Entriken
William Entriken

Reputation: 39243

You can't.

This is a stupid solution as a huge workaround.

  1. Read each contact
  2. Normalize the phone number (not the easiest thing to do!)
  3. Cache contacts into a [String : Contact]

Then you can lookup contacts with contacts[phone_number]?

Upvotes: 3

xiaoming
xiaoming

Reputation: 130

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

Upvotes: 5

Related Questions