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?

Indrajeet
  • 5,490
  • 2
  • 28
  • 43
erdemgc
  • 1,701
  • 3
  • 23
  • 43
  • 4
    It seems just too obvious, but are you sure that you access your navigationController correclty? I.e, self.navigationController is not nil? – ullstrm Aug 20 '14 at 08:55

4 Answers4

98

You need to unwrap your navigationController correctly

if let navController = self.navigationController {
    navController.popViewController(animated: true)
}
FredLoh
  • 1,804
  • 18
  • 27
karlofk
  • 1,205
  • 8
  • 15
24

Swift 3.0 This is working for me

self.navigationController?.popViewController(animated: true)

enter image description here

Marco Weber
  • 829
  • 10
  • 19
Anit Kumar
  • 8,075
  • 1
  • 24
  • 27
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.

spaceMonkey
  • 4,475
  • 4
  • 26
  • 34
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.

Aleksi Sjöberg
  • 1,454
  • 1
  • 12
  • 34