iosswiftaddressbookui

How to extract name from a contact in iOS?


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.


Solution

  • 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
    }