18

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!

flohei
  • 5,248
  • 10
  • 36
  • 61

2 Answers2

23

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))
}
Eric Schramm
  • 288
  • 2
  • 8
2
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()])
ddiego
  • 3,247
  • 1
  • 28
  • 18
  • Isn't that different from https://developer.apple.com/documentation/contacts/cncontactformatter/1397746-descriptorforrequiredkeys ? – benc Apr 21 '18 at 07:46