Can I use the View CNContactViewController without saving the contact to the contactStore?

1.7k Views Asked by At

I searched now for at least 2 hours and couldn't find an answer for this.

I need to have an object of type CNContact. I found the CNContactViewController and this view would meet perfectly my requirements. With it I can create a new contact with the predefined view and this gives me an CNContact object.

This is my problem: The CNContactViewController saves the created contact to the contactStore. But I don't want this. Can I suppress this behaviour? I'm pretty sure there must be a solution.

This is my code for creation of the ViewController:

let contactController = CNContactViewController(forNewContact: nil)

contactController.allowsEditing = true
contactController.allowsActions = false

contactController.displayedPropertyKeys = [CNContactPostalAddressesKey, CNContactPhoneNumbersKey, CNContactGivenNameKey]

contactController.delegate = self

contactController.view.layoutIfNeeded()

let navigationController = UINavigationController(rootViewController: contactController)
self.present(navigationController, animated: true)

Here I would like to use the contact without having it in the Addressbook:

func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
    viewController.navigationController?.dismiss(animated: true)
}

Thanks for your help!

2

There are 2 best solutions below

0
matt On

But I don't want this. Can I suppress this behavior? I'm pretty sure there must be a solution.

There isn’t. If the user saves the edited contact (taps Done) then by the time you hear about it, it has been saved into the contacts database and there is nothing you can do about it.

Of course you can turn right around and delete the saved contact. But you cannot prevent the saving from taking place to begin with.

0
Kim Rasmussen On

I'm doing something like this:

let contact = CNMutableContact()
contact.contactType = .person
contact.givenName = "giveName"

let cvc = CNContactViewController(forUnknownContact: contact)
cvc.delegate = self
cvc.contactStore = CNContactStore()
cvc.allowsEditing = false
self.navigationController?.pushViewController(cvc, animated: true)

You can allow the user to save the contact to the internal contact store - but it is not stored automatically.

Remember to implement the delegate functions (fx as an extension)

extension MyContactsViewController: CNContactViewControllerDelegate {
    func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
        viewController.dismiss(animated: true, completion: nil)
    }

    func contactViewController(_ viewController: CNContactViewController, shouldPerformDefaultActionFor property: CNContactProperty) -> Bool {
        print(property.key)
        return true
    }
}