Search code examples
iosswiftaddressbookaddressbookui

Adding and Saving New Contact to AddressBook


I have a problem that I can't quite seem to solve even though I've used resources I've found on Google and on here. I've only started being taught Swift and how to use Xcode about a month ago, hence, I'm very new, and the problem I have is probably very simple to others.

What I'm trying to do is add and save a new contact to the addressbook. I can get from the app to the Contacts app no problem, it's just I can't save the new contact information.

import AddressBookUI
import AddressBook

class ViewController: UIViewController {

    @IBOutlet weak var contactLink: UIButton!

    @IBAction func contactLink(sender: AnyObject) {
        var viewController: ABNewPersonViewController = ABNewPersonViewController()
        self.presentViewController(viewController, animated: true, completion: nil)
    }
}

Here's the code I'm using that relates to my problem. Any assistance will be appreciated.


Solution

  • Nowadays, you'd use ContactsUI framework. So, in Swift 3, you could do:

    import ContactsUI
    
    class ViewController: UIViewController, CNContactViewControllerDelegate {
    
        @IBAction func contactLink(_ sender: AnyObject) {
            let controller = CNContactViewController(forNewContact: nil)
            controller.delegate = self
            let navigationController = UINavigationController(rootViewController: controller)
            self.present(navigationController, animated: true)
        }
    
        func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
            viewController.navigationController?.dismiss(animated: true)
        }
    
    }
    

    My original answer, using AddressBookUI framework in Swift 2 is below.


    The Swift code is:

    import AddressBookUI
    
    class ViewController: UIViewController, ABNewPersonViewControllerDelegate {
    
        @IBAction func contactLink(sender: AnyObject) {
            let controller = ABNewPersonViewController()
            controller.newPersonViewDelegate = self
            let navigationController = UINavigationController(rootViewController: controller)
            self.presentViewController(navigationController, animated: true, completion: nil)
        }
    
        func newPersonViewController(newPersonView: ABNewPersonViewController!, didCompleteWithNewPerson person: ABRecord!) {
            newPersonView.navigationController?.dismissViewControllerAnimated(true, completion: nil);
        }
    }
    

    See the Prompting the User to Create a New Person Record section of the Address Book Programming Guide: User Interaction: Prompting for and Displaying Data.