Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which keys do I need for CNContactFormatter?

I'm trying to format a contact's name using the new CNContactFormatter. It looks like, I didn't fetch all needed name properties of the contact.

Terminating app due to uncaught exception 'CNPropertyNotFetchedException', reason: 'A property was not requested when contact was fetched.'

Does anyone know which ones are required? I tried fetching the following amongst a few others with no luck:

        CNContactNamePrefixKey,
        CNContactGivenNameKey,
        CNContactFamilyNameKey,
        CNContactMiddleNameKey, 
        CNContactPreviousFamilyNameKey,
        CNContactNameSuffixKey,
        CNContactNicknameKey,
        CNContactPhoneticGivenNameKey,
        CNContactPhoneticMiddleNameKey,
        CNContactPhoneticFamilyNameKey,
        CNContactOrganizationNameKey,
        CNContactDepartmentNameKey,
        CNContactJobTitleKey,

Neither the CNContactFomatter Class Reference nor the fetching method's documentation give any clue.

Thanks!

like image 551
flohei Avatar asked Oct 28 '15 06:10

flohei


2 Answers

I found this in the WWDC Session 223 (starting at slide 74) and this worked for me when I was having the same problem. Use CNContactFormatter.descriptorForRequiredKeysForStyle... in the contact selection call. Example:

let contactStore = CNContactStore()
let predicate = CNContact.predicateForContactsMatchingName("John")
let foundContacts = try contactStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
for contact in foundContacts {
            print(CNContactFormatter.stringFromContact(contact, style: .FullName))
}
like image 84
Eric Schramm Avatar answered Nov 12 '22 19:11

Eric Schramm


class func descriptorForRequiredKeys()

Use to fetch all contact keys required to create vCard data from a contact.

https://developer.apple.com/reference/contacts/cncontactvcardserialization

Example:

let containerResults =  try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])
like image 1
ddiego Avatar answered Nov 12 '22 19:11

ddiego