简体   繁体   中英

iOS: After app launched, UIApplication.sharedApplication.keyWindow.rootViewController==nil

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.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM