Crashalot
Crashalot

Reputation: 34513

Cancel button has no effect for CNContactViewController

This is not a dupe of this question or this question because those answers didn't work.

For some reason, the cancel button has no effect when presenting a CNContactViewController inside a UINavigationController.

Steps to reproduce:

  1. Copy this view controller.
  2. Tap cancel button.

Expected behavior:

The CNContactViewController gets dismissed.

Actual behavior:

Nothing happens. Breakpoints inside the delegate function never get called.

import Foundation
import Contacts
import ContactsUI


class ContactViewController: UIViewController, CNContactViewControllerDelegate {


    override func viewDidLoad() {
        super.viewDidLoad()

        createContact()
    }


    func createContact() {
        let contactController = CNContactViewController(forNewContact: nil)

        contactController.delegate = self
        contactController.allowsEditing = true
        contactController.allowsActions = true
        contactController.title = ""
        contactController.view.layoutIfNeeded()

        let contactNavController = UINavigationController(rootViewController: contactController)
        contactNavController.navigationBar.backgroundColor = UIColor.red

        present(contactNavController, animated:true)
    }


    // =============================================================================================================
    // MARK: CNContactViewControllerDelegate Functions
    // =============================================================================================================
    func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
        viewController.dismiss(animated: true, completion: nil)
        dismiss(animated: true, completion: nil)
        print("hi")
    }


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


    // =============================================================================================================
    // MARK: UIViewController Functions
    // =============================================================================================================
    override var prefersStatusBarHidden: Bool {
        return true
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Upvotes: 2

Views: 1206

Answers (1)

Fa.Shapouri
Fa.Shapouri

Reputation: 1048

I have tried your code right now; And cancel button dismiss view controller without problem. The problem in my case was about showing view controller which fixed by change the present of contactNavController to:

DispatchQueue.main.async {
            self.present(contactNavController, animated:true)
        }

try it, maybe you have thread problem

Upvotes: 2

Related Questions