Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why window is nil in AppDelegate

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?

like image 528
FrozenHeart Avatar asked Nov 23 '14 19:11

FrozenHeart


People also ask

What is the difference between AppDelegate and SceneDelegate?

AppDelegate is responsible for handling application-level events, like app launch and the SceneDelegate is responsible for scene lifecycle events like scene creation, destruction and state restoration of a UISceneSession.

What is use of AppDelegate in Swift?

Overview. Your app delegate object manages your app's shared behaviors. The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system.


1 Answers

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.

like image 53
jrturton Avatar answered Sep 19 '22 12:09

jrturton