Which keys do I need for CNContactFormatter?
Asked Answered
A

2

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!

Acclamation answered 28/10, 2015 at 6:8 Comment(0)
I
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))
}
Inadvisable answered 1/11, 2015 at 4:8 Comment(2)
Oh man, thank you! That works like a charm, even combined with some additional fields.Acclamation
WOW. Deep cut. Thank you so much for sharing this solution!Paulettapaulette
H
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()])
Hales answered 15/9, 2016 at 13:58 Comment(1)
Isn't that different from developer.apple.com/documentation/contacts/cncontactformatter/… ?Preparation

© 2022 - 2024 — McMap. All rights reserved.