Search code examples
iosswiftabaddressbook

How to get Full Name of Contacts in Swift


Now am using this code to fetch the contacts from my phone:

 var addressBookReff: ABAddressBookRef = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
    let people:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBookReff).takeRetainedValue()
    for person in people{
        if  let name:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
            let numbers:ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
            if let number:String = ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String {
                self.arrOfDictContacts.addObject(["\(name)":"\(number)"])
            }
        }
    }

Here, am using kABPersonFirstNameProperty to get only the first name.

I want to get the full name of the contacts!!!

If I use, kABPersonCompositeNameFormatFirstNameFirst then am getting error as Int is not convertible toABPropertyId

Pardon me If this question is simple and have many answers, I could find any of them working for me as I dont want to call extra function.

So how can I get the full name and add it to the dictionary arrOfDictContacts ?


Solution

  • In the AddressBook API, you can get the full/composite name with the following code:

    let name = ABRecordCopyCompositeName(person).takeRetainedValue()
    

    In the Contacts API (for iOS 9+), you can use this code:

    let name: String? = CNContactFormatter.string(from: contact, style: .fullName)