Swift 3 添加新联系人 phone 和电子邮件信息

Swift 3 add new contact with phone and email information

我正在尝试提示用户创建新联系人并传递信息。 (特别是 phone 和电子邮件)

我找到了许多使用 CNMutableContact 并向其添加电子邮件的示例。但是,任何涉及 CNContact 的代码都会给我一个 "Use of undeclared type" 错误。

如何设置我的 class 以提示用户保存联系人?

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

你可以这样做。

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")
        }
    }
}

Swift 4

import ContactsUI

实施委托CNContactViewControllerDelegate

@IBAction func UserTap_Handler(_ sender: Any) {

        self.navigationController?.isNavigationBarHidden = false
        let con = CNContact()
        let vc = CNContactViewController(forNewContact: con)
        vc.delegate = self
        _ = self.navigationController?.pushViewController(vc, animated: true)
    }

    //MARK:- contacts delegates
    func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
        print("dismiss contact")
        self.navigationController?.popViewController(animated: true)
    }
    func contactViewController(_ viewController: CNContactViewController, shouldPerformDefaultActionFor property: CNContactProperty) -> Bool {
        return true
    }