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?
There are 2 places you could be getting the crash.
detailsArticle
is not set as "detail".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:
<StoryboardName>.storyboard
where the current UIViewController
sub-class is located and select the current UIViewController
scene.Menu bar
choose Editor
and Embedd In
and select Navigation Controller
.