Swift 3 add new contact with phone and email information

TheMooCows237 picture TheMooCows237 · Jan 20, 2017 · Viewed 7.7k times · Source

I'm trying to prompt the user to create a new contact and pass in information. (specifically a phone and email)

I've found numerous examples of using a CNMutableContact and adding an email to it. However, any of the code involving the CNContact gives me a "Use of undeclared type" error.

How can I setup my class to prompt the user to save the contact?

Answer

Ganesh Kumar picture Ganesh Kumar · Jan 20, 2017
import ContactsUI

//add CNContactViewControllerDelegate to your ViewController
class ViewController: UIViewController , CNContactViewControllerDelegate {

func addPhoneNumber(phNo : String) {
  if #available(iOS 9.0, *) {
      let store = CNContactStore()
      let contact = CNMutableContact()
      let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue :phNo ))
      contact.phoneNumbers = [homePhone]
      let controller = CNContactViewController(forUnknownContact : contact)
      controller.contactStore = store
      controller.delegate = self
      self.navigationController?.setNavigationBarHidden(false, animated: true)
      self.navigationController!.pushViewController(controller, animated: true)
  }
}