Search code examples
swift3uinavigationcontroller

Can't push from programmatically created UINavigationController


In a Swift 3 project using Xcode 8.3 and iOS 10.3, I get a navigation controller to push. The app runs with a navigation controller until I try to use it to push. All works until the last line which cause an app crash, fatal error: unexpectedly found nil while unwrapping an Optional value. I don't want to use the storyboard, the point of this question is how to accomplish this task without the storyboard.

App Delegate code

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        window = UIWindow(frame: UIScreen.main.bounds)

        window?.makeKeyAndVisible()

        window?.rootViewController = UINavigationController(rootViewController: MainViewController())

}

View Controller:

import UIKit

class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        let navController = navigationController

        let myProfileViewController = MyProfileViewController()

        navController!.pushViewController(myProfileViewController, animated: true)

    }
}        

Solution

  • Move

    let navController = navigationController
    let myProfileViewController = MyProfileViewController()
    
    navController!.pushViewController(myProfileViewController, animated: true)
    

    from viewDidLoad to viewDidAppear.

    In viewDidLoad there is no parent navigation controller set up and you should not start animations from there.