3
votes

I'm opening a navigation controller from a button click of my main view controller.

I programatically created a left bar button item on the navigation controller which I want to dismiss the nav controller and go back to my main controller.

I'm essentially going back on the root view controller of the navigation controller.

I've tried

navigationController?.dismissViewControllerAnimated(true, completion: nil)

and

self.dismissViewControllerAnimated(true, completion: nil)

and get an NSException on both.

Please advise.

6
What NSException do you get?matt
Are you pushing or presenting the UIViewController?Sohil R. Memon
May be you're calling these method on rootViewController itself. what exception you are getting, BTW?Suryakant Sharma
sounds more like a usecase for unwind segues: stackoverflow.com/questions/12561735/…Christian Dietrich
unrecognized selector sent to instance 0x154da4960 2016-03-17 19:16:29.363 [605:192637] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ back:]: unrecognized selector sent to instance 0x154da4960'Walking

6 Answers

9
votes

Swift 3:

self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)

It will dismiss all the presented view controllers and remain root view controller.

4
votes

If you are pushing your ViewController, you should use pop to remove that ViewController from Navigation Stack and land on the previous ViewController. Try this...

self.navigationController?.popViewControllerAnimated(true);

SWIFT 3

_ = navigationController?.popViewController(animated: true);
0
votes

dismissViewController works when you are showing a viewController using presentViewController, that maybe the root view controller of a navigation stack, or a stand alone view controller.

0
votes
self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)

Try this :)

0
votes

A year later.. The exception indicates that there is something wrong with the selector that you provide to the action param, when adding the left bar button.

Something like this should work:

creating bar button item:

let backBarButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(dismissView))

dismiss root view controller:

func dismissView() {
    self.dismiss(animated: true, completion: nil)
}
0
votes

Apple Dev already provides very simple code which is

self.navigationController?.popToRootViewController(animated: false)