Why window is nil in AppDelegate

14,948

You need to create the window yourself in AppDelegate if not using the main interface option:

self.window = UIWindow(frame:UIScreen.mainScreen().bounds)

Swift 3.0+

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

Then call your code above, using window.

Finally, call makeKeyAndVisible() on the window.

Share:
14,948

Related videos on Youtube

FrozenHeart
Author by

FrozenHeart

Updated on July 12, 2022

Comments

  • FrozenHeart
    FrozenHeart almost 2 years

    I need to present view controller from the AppDelegate, so I wrote the following code:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let authViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
    if let keyWindow = UIApplication.sharedApplication().keyWindow {
        keyWindow.rootViewController = authViewController
    }
    

    Unfortunately, window and keyWindow are both nil. Why?

    • jrturton
      jrturton over 9 years
      When is this code being executed?
    • FrozenHeart
      FrozenHeart over 9 years
      @jrturton This is code is execute in the func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool function
    • jrturton
      jrturton over 9 years
      Ok, in that function your app won't have a window unless you've made one manually, or you've set a storyboard or xib as the launch interface. Have you done that?
    • FrozenHeart
      FrozenHeart over 9 years
      @jrturton No. How can I do it via Interface Builder?
  • FrozenHeart
    FrozenHeart over 9 years
    I don't want to automatically load the initial view controller, because I need to present either authorization view controller or the main view controller manually
  • FrozenHeart
    FrozenHeart over 9 years
    Thanks for the answer! btw, window doesn't have makeKeyAndOrderFront function
  • FrozenHeart
    FrozenHeart over 9 years
    It works as expected without makeKeyAndVisible function call too. Is it necessary?
  • jrturton
    jrturton over 9 years
    It was always there on the templates so I assumed so. Don't know.
  • Mitesh Mewada
    Mitesh Mewada almost 3 years
    for Swift 5 self.window = UIWindow(frame:UIScreen.main.bounds)