How to extract name from a contact in iOS?

1.3k views Asked by At

I have picked up a contact from the address book

Now I need to display the name to the text view UI in the same view controller.

How to extract the name from the ABRecord?

This is my code.

@IBAction func addContact(sender: AnyObject) {
    var peoplePicker = ABPeoplePickerNavigationController()
    peoplePicker.peoplePickerDelegate = self
    self.presentViewController(peoplePicker, animated: true, completion: nil)

}

func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController!) {
    dismissViewControllerAnimated(true, completion: nil)
}


func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!) {

    var name : String! = ABRecordCopyCompositeName(person)
}

Here the function ABRecordCopyCompositeName return unmanaged I can't force cast to String. It says not convertible.

I'm new to iOS dev. please help.

2

There are 2 answers

0
Vitalii Gozhenko On BEST ANSWER

Use takeUnretainedValue() and takeRetainedValue() to get CFString object and cast it to NSString

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!) {
    let nameCFString : CFString = ABRecordCopyCompositeName(person).takeRetainedValue()
    let name : NSString = nameCFString as NSString
}
0
Kamil On

You can also check KBContactsSelection which allows you to search and select multiple contacts and is easily customizable using elegant Builder Pattern.

KBContactsSelection screen