Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 add new contact with phone and email information

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?

like image 630
TheMooCows237 Avatar asked Jan 20 '17 04:01

TheMooCows237


People also ask

How do I add contacts in Swift?

Add contact with a button click using swift 3emailAddresses = [workEmail] newContact. phoneNumbers = [CNLabeledValue( label:CNLabelPhoneNumberiPhone, value:CNPhoneNumber(stringValue:"0123456789"))] do { let saveRequest = CNSaveRequest() saveRequest. add(newContact, toContainerWithIdentifier: nil) try AppDelegate.

How do I access my phone contacts in Swift?

Swift 4 and 5. import ContactsUI func phoneNumberWithContryCode() -> [String] { let contacts = PhoneContacts. getContacts() // here calling the getContacts methods var arrPhoneNumbers = [String]() for contact in contacts { for ContctNumVar: CNLabeledValue in contact. phoneNumbers { if let fulMobNumVar = ContctNumVar.


2 Answers

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)
  }
}
like image 165
Ganesh Kumar Avatar answered Sep 18 '22 09:09

Ganesh Kumar


You Can Do Something Like This.

extension ViewController: CNContactViewControllerDelegate {

    func showNewContactViewController() {

        let contactViewController: CNContactViewController = CNContactViewController(forNewContact: nil)
        contactViewController.contactStore = CNContactStore()
        contactViewController.delegate = self
        let navigationController: UINavigationController = UINavigationController(rootViewController: contactViewController)
        present(navigationController, animated: false) {
            print("Present")
        }
    }
}
like image 30
Satish Babariya Avatar answered Sep 19 '22 09:09

Satish Babariya