How to get Full Name of Contacts in Swift
Asked Answered
B

1

16

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 ?

Barayon answered 9/9, 2015 at 21:46 Comment(0)
D
40

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)
Deleterious answered 9/9, 2015 at 22:14 Comment(3)
what is the record here?Barayon
Updated to swift 3: let name = CNContactFormatter.string(from: contact, style: .fullName)Raccoon
u also need to add this CNContactFormatter.descriptorForRequiredKeys(for: .fullName) as CNKeyDescriptor in the keys of CNContactFetchRequest, otherwise app will crash.Selfseeking

© 2022 - 2024 — McMap. All rights reserved.