如何正确处理一个无UIApplication.sharedApplication()。keyWindow [英] How to properly handle a nil UIApplication.sharedApplication().keyWindow

查看:357
本文介绍了如何正确处理一个无UIApplication.sharedApplication()。keyWindow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

viewDidLoad 被调用时,视图应该被加载。



code> UIApplication.sharedApplication()。keyWindow 是nil ...



我应该把我的代码让它调用一次视图被加载,而不是每次用户回来(我已经排除了viewWillAppear因为这个原因)?

解决方案

情况1: - 手动 UIWindow 在应用程序委托中创建



您可能以某种方式向 UIWindow 添加了 UIViewController / code>,然后将其设为键。



您应该在您的电脑上调用 window.makeKeyAndVisible()


$ b

情境2: - 自动创建脚本实例化

>系统读取您的故事板,初始化根视图控制器,通过调用 viewDidLoad viewWillAppear



会发生什么是系统不能只是将窗口设置为前端,并将视图控制器设置为动画,因为它是第一个视图控制器和你不是推/弹出一个nav控制器。和 viewDidLoad 可能需要一些时间...因此, Default.png 同时显示,直到视图控制器



然后,当它实际出现时,它调用 viewDidAppear 。这是 能够访问 keyWindow



情况3:



你有一个奇怪的情况,你有窗口,但没有一个是关键窗口目前,但你迫切需要访问



调用 UIApplication.sharedApplication()。windows ,看看它是否为空并获取第一个元素。 UIApplication.sharedApplication()。delegate?.window 可能有一个值,但通常只有当窗口是 >

When the viewDidLoad is called the view is supposed to be loaded.

But I always crash in UIApplication.sharedApplication().keyWindow being nil...

Where should I put my code to have it called once the view is loaded and not everytime the user comes back (I have excluded viewWillAppear for that reason) ?

解决方案

Situation 1: - Manual UIWindow creation in App's delegate

You have probably somehow added a UIViewController to a UIWindow before setting it as key.

You should call window.makeKeyAndVisible() in your app's delegate after creating the window.

Situation 2: - Automatic storyboard instantiation

The system reads your storyboard, initializes the root view controller, prepares it by calling viewDidLoad and viewWillAppear, adds it to the window and shows the window.

What happens is the system cannot just set the window to the front and animate the view controller onto it, because it's the first view controller and you are not push/popping of a nav controller. And viewDidLoad can take some time... So the Default.png is showing in the meanwhile until the view controller is ready.

Then it calls viewDidAppear, when it has actually appeared. So that's where you should be able to access a keyWindow

Situation 3:

You are in a weird situation where you have windows but none of them is the "key" window currently, but you desperately need to access the window.

Call UIApplication.sharedApplication().windows, see if it's not empty and take the first element. UIApplication.sharedApplication().delegate?.window might have a value too, but it's usually only when the window is key already.

这篇关于如何正确处理一个无UIApplication.sharedApplication()。keyWindow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆