1

I am using the new version of retrieving contacts from the Phonebook on iOS. There is a problem with the unique identifier, which is returned by the first query. Normally the unique identifier is a UUID, but sometimes it is appended by “: ABPerson”. Querying the Phonebook API with this identifier works sometimes, but not always. Does anybody know, if there is a way to avoid this behaviour? Currently, I try with a safeguard of two queries. The first is using the identifier as is, the second (if the first fails) is to use the identifier stripping the “: ABPerson” extension.

The first query used is:

class func getAllPhoneBookContacts() -> [PhonebookContact] {
    let contactStore = CNContactStore()
    var contacts = [PhonebookContact]()
    PhoneBookContactsHelper.requestForAccess { (accessGranted) -> Void in
        if accessGranted {
            let keys = [CNContactIdentifierKey, CNContactPhoneNumbersKey]

            do {
                let fetchRequest = CNContactFetchRequest(keysToFetch: keys)
                try contactStore.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (contact: CNContact, _) -> Void in
                    for phoneNoLab in contact.phoneNumbers {
                        if let phoneNo = phoneNoLab.value as? CNPhoneNumber,
                        normalizedPhoneNumber = PhoneNumberNormalizer.normalizePhoneNumber(phoneNo.stringValue) {
                            let pbc = PhonebookContact(contactID: contact.identifier, phoneNumber: normalizedPhoneNumber)
                            contacts.append(pbc)
                        }
                    }
                })
            }
            catch {
                NSLog("Unable to fetch contacts.")
            }
        }
    }
    return contacts
}

Accessing a certain contact again later by the identifier is done by:

class func getContactNameByUUID(identifier: String) -> String?{
    var name : String?
    PhoneBookContactsHelper.requestForAccess()
        { (accessGranted) -> Void in
            if accessGranted {
                let contactStore = CNContactStore()
                let keys = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
                do {
                    let cnc = try contactStore.unifiedContactWithIdentifier(identifier, keysToFetch: keys)
                    name = CNContactFormatter.stringFromContact(cnc, style: .FullName)!
                }
                catch _ {
                    NSLog("Could not fetch contact with id \(identifier))")
                }
            }
    }
    return name
}

I am using iOS 9 and tested on simulator and various iPhones and the unexpected behaviour is present everywhere.

mjrehder
  • 317
  • 4
  • 11

0 Answers0