简体   繁体   中英

CNContactViewController Cancel Button Not Working

I'm trying to use the built-in new contact UI and am getting unexpected behavior with the cancel button. The code below works and calls up the new contact screen but the cancel button will only clear the screen entries not cancel out of the new contact screen. In the built in contacts app hitting cancel returns to the contact list screen. I would like the cancel button to close out the window.

@IBAction func newTwo(sender: AnyObject) {
    AppDelegate.getAppDelegate().requestForAccess { (accessGranted) -> Void in
        if accessGranted {
            let npvc = CNContactViewController(forNewContact: nil)
            npvc.delegate = self
            self.navigationController?.pushViewController(npvc, animated: true)
         }
    }

}

did you implement CNContactViewControllerDelegate methods? Here's a link to documentation

for example:

 func contactViewController(viewController: CNContactViewController, didCompleteWithContact contact: CNContact?) {

    self.dismissViewControllerAnimated(true, completion: nil)
}

Better way to do the dismissing would be to check if the contact is nil and then dismiss it. The dismiss doesn't work if you've pushed the view controller from a navigation controller. You might have to do the following:

func contactViewController(viewController: CNContactViewController, didCompleteWithContact contact: CNContact?) {
  if let contactCreated =  contact
  {

  }
  else
  {
    _ = self.navigationController?.popViewController(animated: true)
  }
}

It worked for me using the following code:

Swift 3

func contactViewController(_ vc: CNContactViewController, didCompleteWith con: CNContact?) {
    vc.dismiss(animated: true)
}

Also I changed the way I was calling the controller:

Instead of:

self.navigationController?.pushViewController(contactViewController, animated: true)

the solution was:

self.present(UINavigationController(rootViewController: contactViewController), animated:true)

I found the solution using the example code Programming-iOS-Book-Examples written by Matt Neuburg :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM