swiftnavigationcontroller

navigationController!.pushViewController giving Fatal error: Unexpectedly found nil while unwrapping an Optional value:


I am trying to navigate from one Storyboard to another Storyboard. Here is my code -

  let storyboard = UIStoryboard(name: "Main", bundle: nil)
                     let controller = storyboard.instantiateViewController(withIdentifier: "detail") as! detailsArticle
                     controller.jsonData = json2["post"]
                    
                    self.navigationController!.pushViewController(controller, animated: true)
            

However, when I try to navigate after clicking the button which runs the above code, I get exception error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value: file

How do I solve this?


Solution

  • There are 2 places you could be getting the crash.

    1. The identifier of the detailsArticle is not set as "detail".
    2. The controller you're trying to push onto is not embedded in navigationController.

    Try running and check the console to see the debug messages I've added:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let controller = storyboard.instantiateViewController(withIdentifier: "detail") as? detailsArticle else { print("detail vc id not set"); return }
    controller.jsonData = json2["post"]
    guard let navigationController = navigationController else { print("this vc is not embedded in navigationController"); return }
    navigationController.pushViewController(controller, animated: true)
    

    From the comments it's the 2nd one causing the issue. To fix it here are the steps:

    1. Go to <StoryboardName>.storyboard where the current UIViewController sub-class is located and select the current UIViewController scene.
    2. From the Menu bar choose Editor and Embedd In and select Navigation Controller.