How to properly handle a nil UIApplication.sharedA

2020-02-26 01:19发布

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) ?

3条回答
The star\"
2楼-- · 2020-02-26 01:30

Try using the window property of the application delegate:

UIApplication.sharedApplication().delegate!.window
查看更多
够拽才男人
3楼-- · 2020-02-26 01:44

If you get nil from "UIApplication.shared.keyWindow" at "viewDidLoad", Try wrap your code inside of DispatchQueue.

ex)

override func viewDidLoad() {
    DispatchQueue.main.async {
        if var window = UIApplication.shared.keyWindow {
            // do something
        }
    }
}
查看更多
虎瘦雄心在
4楼-- · 2020-02-26 01:48

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.

查看更多
登录 后发表回答