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.
Related videos on Youtube
Author by
FrozenHeart
Updated on July 12, 2022Comments
-
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
andkeyWindow
are bothnil
. Why?-
jrturton over 9 yearsWhen is this code being executed?
-
FrozenHeart over 9 years@jrturton This is code is execute in the
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
function -
jrturton over 9 yearsOk, 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 over 9 years@jrturton No. How can I do it via Interface Builder?
-
-
FrozenHeart over 9 yearsI 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 over 9 yearsThanks for the answer! btw,
window
doesn't havemakeKeyAndOrderFront
function -
FrozenHeart over 9 yearsIt works as expected without
makeKeyAndVisible
function call too. Is it necessary? -
jrturton over 9 yearsIt was always there on the templates so I assumed so. Don't know.
-
Mitesh Mewada almost 3 yearsfor Swift 5
self.window = UIWindow(frame:UIScreen.main.bounds)