50

I need to pop a UIViewController from the navigation controller.

Just writing this line of code but taking an exception;

unexpectedly found nil while unwrapping an Optional value

self.navigationController.popViewControllerAnimated(true)

If I make the navigation controller optional, this line makes no effect, no popping

self.navigationController?.popViewControllerAnimated(true)

How to solve it?

1
  • 4
    It seems just too obvious, but are you sure that you access your navigationController correclty? I.e, self.navigationController is not nil?
    – ullstrm
    Commented Aug 20, 2014 at 8:55

4 Answers 4

99

You need to unwrap your navigationController correctly

if let navController = self.navigationController {
    navController.popViewController(animated: true)
}
2
  • 29
    This basically has the same effect as optional chaining; it works if it's not nil and does nothing if it is. Commented Aug 21, 2015 at 6:27
  • 7
    This is no different than the question's code in effect. Commented Feb 27, 2018 at 23:42
25

Swift 3.0 This is working for me

self.navigationController?.popViewController(animated: true)

enter image description here

2
  • 5
    _ = is not needed here
    – seanscal
    Commented Apr 19, 2017 at 19:46
  • 1
    If you are not using return type of variable then you can written like this _ =
    – Anit Kumar
    Commented Apr 27, 2017 at 18:39
9

In my case im using a Master Details view ( Split View Controller ). My details view controller is embedded inside an navigation controller. So when i wanted to dismiss my Details view controller. I had to pop it from the navigation controller of the parent (Split view controller) Like this.

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

hope this helps someone.

2
  • 1
    Yes! I needed to get the navigationController of the navigationController!! Commented Mar 13, 2018 at 23:10
  • Wow! Works in the case of split view controller. +1
    – Codetard
    Commented Nov 10, 2021 at 5:16
6

It seems that the view controller you're working with isn't embedded in Navigation Controller. If there was a Navigation Controller, i.e. self.navigationController is not nil, both lines should work just as well even though the latter one is preferred as it uses optional chaining.

Make sure you have embedded your View Controller in a Navigation Controller. You can do it by selecting the View Controller in Storyboard editor and clicking Editor -> Embed In -> Navigation Controller. Also make sure that you have your Storyboard Entry Point (the arrow that indicates which view controller is presented first) either pointing to Navigation Controller or before it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.