UIApplication sharedApplication - keyWindow is nil?

送分小仙女□ 提交于 2019-11-27 23:26:13

This code was executed before [window makeKeyAndVisible]; which is inside the app delegate. So, no wonder why keyWindow was nil yet.

Easiest way is to get the window from the app delegate instead:

UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
// Do something with the window now
albertodebortoli

I noticed that after having started the Guided Access, the keyWindow property on [UIApplication sharedApplication] appears to be nil.

It happened to me only on iOS7 when starting the Guided Access Mode for the first time after having enabled it in Settings > General > Guided Access, so the starting GAM view is actually displayed and not by-passed.

Since this Apple API seems buggy, I solved using the following code to retrieve the window I'm looking for.

NSArray *windows = [[UIApplication sharedApplication] windows];
if ([windows count]) {
    return windows[0];
}
return nil;

Instead of

[[UIApplication sharedApplication] keyWindow];

maybe you could also try using

[[[UIApplication sharedApplication] delegate] window];

as iWasRobbed pointed out but it wasn't working for me as the rootViewController property isn't reachable this way.

Try this, first get the UINavigationController handle, and then the topViewController

let navController = window?.rootViewController as! UINavigationController
let yourMainViewController = navController.topViewController as! ItemsViewController

or

let yourMainViewController = navController.viewControllers.first as! ItemsViewController
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!