How to fix AppDelegate's window == nil in project with scenes?

Viewed 150

There are some similar questions but they are all about how to get window when project uses scenes. But my one is slightly different.

You propose to get the active window via the different way - it is ok. But what to do with old libraries (in my case it is custom activity views) which access to the optional window property with "implicitly unwrapping": appDelegate.window!

Is it possible to override appDelegate.window property getter to return the current window?

1 Answers

Here is possible approach

1) declare window property in app delegate

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    ...

2) assign it explicitly in scene on window showing (or creation, which place is preferable)

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        ...
        window.makeKeyAndVisible()
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.window = window
        }
Related