Search code examples
iosabaddressbook

contactViewController didCompleteWith contact is nil


I'm trying to add a new contact copying an existing contact's values.

if let mutableContact = self.editingCard?.contact.mutableCopy() as? CNMutableContact {
    let editCardViewController = CNContactViewController(for: mutableContact)
    editCardViewController.contactStore = CNContactStore()
    editCardViewController.title = "Edit Card"
    editCardViewController.delegate = self
    self.present(UINavigationController(rootViewController: editCardViewController), animated: true, completion: nil)
}

The Contact View Controller displayed is fine. It displays details prefilled from the contact. However, after clicking Done, the callback is called in nil contact reference. i.e.

func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
    print("Completed adding card \(contact)")
}

Any clue what I'm doing wrong?


Solution

  • This seems to happen because of ill formatted information on your CNMutableContact object. In my case the dates (birthday, anniversary and other dates) had minutes, seconds setup on the date objects. As per https://developer.apple.com/reference/contacts/cnmutablecontact/1403311-dates, that use case is invalid.

    For anyone, who may see this issue, debugging through all the information you are setting will be helpful to understand any ill formatted information on your CNMutableContact reference.