David Chelidze David Chelidze - 7 months ago 135
Swift Question

CNContact display name objective c / swift

I am working on app where I need to import contacts into

NSMutableDictionary
, but sometimes people not filling all contact details. So leaving just number or company name. Do I need to go through all contacts detail to check what field will be my "display name". In Android I know there is
displayName
variable. But how it is in Swift or Objective C?

My code:

BOOL success = [addressBook
enumerateContactsWithFetchRequest:request
error:&contactError
usingBlock:^(CNContact *contact, BOOL *stop){

NSString * contactId = contact.identifier;
NSString * firstName = contact.givenName;
NSString * lastName = contact.familyName;
}];

Rob Rob
Answer

Use CNContactFormatter to build the display name. When specifying the keys for the request, use descriptorForRequiredKeysForStyle to make sure you requested the appropriate fields.

In Swift, it would be:

let store = CNContactStore()
store.requestAccessForEntityType(.Contacts) { granted, error in
    guard granted else {
        print(error)
        return
    }

    let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])

    let formatter = CNContactFormatter()
    formatter.style = .FullName

    do {
        try store.enumerateContactsWithFetchRequest(request) { contact, stop in
            print(formatter.stringFromContact(contact))
        }
    } catch let fetchError {
        print(fetchError)
    }
}

You suggested that you have situations where there is neither name nor company, but just phone number. Well, then, you'd have to manually handle that yourself:

let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey, CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])

let formatter = CNContactFormatter()
formatter.style = .FullName

do {
    try store.enumerateContactsWithFetchRequest(request) { contact, stop in
        if let name = formatter.stringFromContact(contact) {
            print(name)
        } else if let firstPhone = contact.phoneNumbers.first?.value as? CNPhoneNumber {
            print(firstPhone.stringValue)
        } else {
            print("no name; no number")
        }
    }
} catch let fetchError {
    print(fetchError)
}
Comments