Search code examples
swiftappdelegateviewdidload

When I set the Viewcontroller is the root navigation controller, I recieve the found nil error


When I set the ViewController is the root navigation controller in the file Appdelegate.swift, like this:

var viewcontroller=ViewController();
var rootnavigationcontroller=UINavigationController.init(rootViewController: viewcontroller);
self.window?.rootViewController=rootnavigationcontroller;

Then I configure the ViewController like this:

class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate{
    @IBOutlet weak var MapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        loadLaunchScreen();
        Initilize();//Here configure the MapView parameters;
    }

Then in the function Initilize(); I receive the error that means the MapView has found nil.

But if I do not set this Viewcontroller as the rootnavigationcontroller in the Appdelegate.swift, I will run well.

I want to ask why and how to solve it?


Solution

  • if you are using storyboards then try this

        let stroyboard = UIStoryboard.init(name: "storyboardname", bundle: nil)//nil if its not out of your project
        let ViewController = storyboard.instantiateViewController(withIdentifier: "yourstoryboadid")
        var rootnavigationcontroller=UINavigationController.init(rootViewController: viewcontroller);
        self.window?.rootViewController=rootnavigationcontroller;
    

    above problem can happen when you use storybords and you are instantiate the viewController not from storyboard thats when your outlet found nil because is is not bounded to the outlet

    if you are not using storyboards then your code is perfet