"Create New Contact" and "Add to Existing Contact" for CNContactViewController()

5813 picture 5813 · Aug 28, 2016 · Viewed 8.2k times · Source

With ABAddressBook, when I wanted the user to be able to have the options of "Create New Contact" and "Add to Existing Contact" for a contact they hadn't seen before, I would create and present an ABUnknownPersonViewController.

I can find no way to replicate this functionality in the CNContacts framework. It seemed to me that CNContactViewController(forUnknownContact: contact) could work, but unfortunately this only lets the user "Send Message" or "Share Contact."

How can I allow a user to save the contact to their address book, either as a new contact or as part of an existing one, in CNContacts?

func presentContact() {

    let status = CNContactStore.authorizationStatusForEntityType(.Contacts)

    switch status {
    case .Authorized: ()
    case .NotDetermined: requestAccess()
    case .Denied, .Restricted: accessDenied()
    }

    print("authorized? \(status == .Authorized)") //prints "authorized? true"

    let unknown = CNContactViewController(forUnknownContact: contact!)

    unknown.delegate = self

    self.navigationController?.pushViewController(unknown, animated: false)

}

Even when I try to request access, the user still can't save the contact.

Answer

matt picture matt · Aug 28, 2016

You keep not showing your real code, so it's impossible to help you. So I've lost interest. I'll just show you my real code instead and leave you to study it and think about the difference between what I'm doing and what you're doing. Here's actual working code; go ye and do likewise:

let con = CNMutableContact()
con.givenName = "Johnny"
con.familyName = "Appleseed"
con.phoneNumbers.append(CNLabeledValue(
    label: "woods", value: CNPhoneNumber(stringValue: "555-123-4567")))
let unkvc = CNContactViewController(forUnknownContact: con)
unkvc.message = "He knows his trees"
unkvc.contactStore = CNContactStore()
unkvc.delegate = self
unkvc.allowsActions = false
self.navigationController?.pushViewController(unkvc, animated: true)

enter image description here