How to properly handle a nil UIApplication.sharedApplication().keyWindow
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 is nil?
This code was executed before [window makeKeyAndVisible];
which is inside the app delegate.
So, no wonder why keyWindow
was nil
yet.
Proper way to pop to another ViewController from a TableViewCell
Had to be called from the root View Controller
by UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(actionSheet, animated: true, completion: nil)
Related Topics
Non-Main Bundle File as Alert Sound
Change Uipopoverview Background + Arrow Color
Dynamic Uitablecellview Height
Scene Kit Memory Management Using Swift
How to Read References Given by Ptr_Refs in iOS
Convert Uiview to .Png in Swift
Get Total Include Months Between 2 Date in Swift
How to Load Thousands Records to Realm Correctly
Swift Parse - Local Datastore and Displaying Objects in a Tableview
Avplayerlayer Shows Black Screen But Sound Is Working
Using Avaudioplayer to Play Remote Mp3 File in Swift
Save Video to a Custom Album Using Photos Framework in iOS
Cgaffinetransformmakerotation with Negative M_Pi
How to Convert Base64 into Nsdata in Swift
Swiftui Card Flip Animation with Two Views, One of Which Is Embedded Within a Stack
Wkwebview Decidepolicyfornavigationaction Being Call After the Long Press Recogniser Ended