I have some code called from my viewWillAppear
that relies on the root view controller's traitCollection being valid. To my surprise, even by the time when viewWillAppear is called, UIApplication.sharedApplication.keyWindow.rootViewController
is still nil, long after it was set and makeKeyWindow
was called.
Why would this be? What is actually going on? It seems like some reasonable assumptions have stopped being true.
Asked
Active
Viewed 1,822 times
0

Ankur Lahiry
- 2,253
- 1
- 15
- 25

eonnu
- 93
- 7
2 Answers
2
The revelation is that not only is keyWindow deprecated, but in fact non-functional and returns nil, after window has been assigned and viewWillAppear has been called.
Therefore, change to this:
UIViewController *vc = UIApplication.sharedApplication.windows.firstObject.rootViewController;

eonnu
- 93
- 7
0
I'm assuming you have not assigned window
property on didFinishLaunchingWithOptions
method
If you have no window property in App Delegate assign, it'll be retained
Do you have a similar code written?
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainVC = UIViewController()
self.window?.rootViewController = mainVC
self.window?.makeKeyAndVisible()
By the way, keyWindow
property is now deprecated
Try this:
UIApplication.shared.windows.first({ $0.isKeyWindow })

Iliya Kisliy
- 241
- 1
- 5
-
But I did assign it. The problem was however that keyWindow is not only deprecated but Not Working. I switched to using UIApplication.sharedApplication.windows.firstObject.rootViewController and it works fine. – eonnu Oct 02 '19 at 17:53