Search code examples
swiftxcodemacoscncontactviewcontroller

How to edit a contact using CNContactViewController on mac OS


I want to create an app that lets the user edit contacts.

According to the docs the CNContactViewController has the property allowsEditing for both iOS and macOS 10.11+.

In Xcode the CNContactViewController has only one property and no contact specific methods:

@NSCopying open var contact: CNContact?

Is it possible at all to edit a contact on the mac using the ContactsUI framework or is this an error in the docs?

This is how I display the contact:

if let vc = segue.destinationController as? CNContactViewController{

    let contact = CNMutableContact()
    contact.givenName = "John"
    contact.familyName = "Appleseed"

    let homeEmail = CNLabeledValue(label:CNLabelHome, value:"john@example.com" as NSString)
    let workEmail = CNLabeledValue(label:CNLabelWork, value:"j.appleseed@icloud.com" as NSString)
    contact.emailAddresses = [homeEmail, workEmail]

    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelPhoneNumberiPhone,
        value:CNPhoneNumber(stringValue:"(408) 555-0126"))]

    let homeAddress = CNMutablePostalAddress()
    homeAddress.street = "1 Infinite Loop"
    homeAddress.city = "Cupertino"
    homeAddress.state = "CA"
    homeAddress.postalCode = "95014"
    contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]

    var birthday = DateComponents()
    birthday.day = 1
    birthday.month = 4
    birthday.year = 1988  // You can omit the year value for a yearless birthday
    contact.birthday = birthday
    vc.contact = contact
}

However, there is no edit button available:

no-edit-button


Solution

  • I used one of my developer credits to ask Apple about this under Sierra, and the reply was that 'edit' functionality is not implemented under macOS yet. It was suggested that I submit a radar (which I did). I was hoping that it would be updated for High Sierra, but alas, no such API yet.

    If you click on the actual 'allowsEditing' link, you will see that for this API, it is only under iOS (for now). Pity - I'm really looking forward to removing my AddressBook code for Contacts code, but I can't yet.