I am trying to allow the user to edit a contact that is defined by the contacts identifier.
The contacts identifier is in - private var theContactID: String = ""
This code opens the CNContactViewController but I don't know how to tell the controller to open the specified contact for editing. I appreciate any help.
private var theContactID: String = ""
let theAlert = UIAlertController(title: NSLocalizedString("ContactNoAddress_String", comment: ""), message: nil, preferredStyle: .alert)
let cancelBtn = UIAlertAction(title: NSLocalizedString("OK_String", comment: ""), style: .cancel) { (cancelAction) in
self.populateThePrintFld()
}
let editBtn = UIAlertAction(title: NSLocalizedString("EditContact_String", comment: ""), style: .default) { (editAction) in
self.requestAccess { (accessGranted) in
let editContact = CNMutableContact()
let vc = CNContactViewController(for: editContact)
vc.allowsEditing = true
vc.delegate = self // delegate for CNContactViewControllerDelegate
DispatchQueue.main.async {
self.present(UINavigationController(rootViewController: vc), animated: true)
}
}
}
theAlert.addAction(cancelBtn)
theAlert.addAction(editBtn)
present(theAlert, animated: true)
To open `CNContactViewController` for editing an existing contact, you need to pass an existing contact to the initializer.
For example:
do {
let descriptor = CNContactViewController.descriptorForRequiredKeys()
let editContact = try store.unifiedContact(withIdentifier: theContactID, keysToFetch: [descriptor])
let vc = CNContactViewController(for: editContact)
//...
} catch {
print(error)
}