ios - How to properly handle a nil UIApplication.sharedApplication().keyWindow -


when viewdidload called view supposed loaded.

but crash in uiapplication.sharedapplication().keywindow being nil...

where should put code have called once view loaded , not everytime user comes (i have excluded viewwillappear reason) ?

situation 1: - manual uiwindow creation in app's delegate

you have somehow added uiviewcontroller uiwindow before setting key.

you should call window.makekeyandvisible() in app's delegate after creating window.

situation 2: - automatic storyboard instantiation

the system reads storyboard, initializes root view controller, prepares calling viewdidload , viewwillappear, adds window , shows window.

what happens system cannot set window front , animate view controller onto it, because it's first view controller , not push/popping of nav controller. , viewdidload can take time... default.png showing in meanwhile until view controller ready.

then calls viewdidappear, when has appeared. that's should able access keywindow

situation 3:

you in weird situation have windows none of them "key" window currently, desperately need access window.

call uiapplication.sharedapplication().windows, see if it's not empty , take first element. uiapplication.sharedapplication().delegate?.window might have value too, it's when window key already.


Comments