Search code examples
iosxcodeswiftuiapplicationdelegate

Initing and assigning a view controller in the applicationDelegate makes all the UI elements in the viewController be nil


In my ApplicationDelegate :

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {

        initMembers()
        runTutorialIfNeeded()
        return true
    }

 func initMembers()
    {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        mainViewController = InlineMainViewController()
        window?.rootViewController = mainViewController
        window?.makeKeyAndVisible()
    }

but this line causes a problem:

mainViewController = InlineMainViewController()

all the UIElements are nil when the code reaches override func viewDidLoad() {

If I comment this line mainViewController = InlineMainViewController() All Ui elements from the main storyboard are not nil

How can I fix this? I need to save a reference of the main viewController in the applicationDelegate in order to interact with it when messageMgr: GNSMessageManager sends event.


Solution

  • You initialized the ViewController wrong. If you're using a storyboard then you should write this:

        let storyboard = UIStoryboard(name: "YourStoryBoardFileName", bundle: nil)
        mainViewController = storyboard.instantiateViewControllerWithIdentifier("your_VC_ID")
        window.rootViewController = mainViewController
        window.makeKeyAndVisible()
    

    If you're using NIB/XIB files then you should write this:

    let mainViewController = YourViewController(nibName:"YourVCNibName", bundle:nil)
    

    If you're just initializing it like InLineViewController(), there's no view attached to it and therefore everything is nil.