iosswiftuiappdelegate

SwiftUI AppDelegate UIWindow redeclaration


I'm using SwiftUI so the AppDelegate is added by

@UIApplicationDelegateAdaptor(MyAppDelegate.self) var myAppDelegate

All delegate callbacks work fine, but var window: UIWindow? can't be redeclared.

Adding it to MyAppDelegate has no effect as if accessing UIApplication.shared.delegate class is not MyAppDelegate but SwiftUI.AppDlegate.

How I can add it to AppDelegate, to make it accessible by UIApplication.shared.delegate.window ?

Or how to set var window: UIWindow? property to SwiftUI.AppDlegate ?


Solution

  • Solution found. Custom MyAppDelegate can contain var window: UIWindow? property:

    class MyAppDelegate: NSObject, ObservableObject, UIApplicationDelegate {
    
    var window: UIWindow?
    
    }
    

    And can be accessed by EnvironmentVariable:

    @EnvironmentObject private var appDelegate: MyAppDelegate
    
    appDelegate.window = <Window object>
    

    Then the correct UIWindow value will be available by UIApplication.shared.delegate.window

    Documentation refference: https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor