What is equivalent to 'window.rootViewController' in WindowGroup - SwiftUI

1.8k views Asked by At

I am new to SwiftUI and facing a problem where I want to change the root view when a certain action occurs inside the app.

How I handle it when using SceneDelegate was as follows

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
       ... // the code of initializing the window

        observeOnChangeWindow()
    }

    func observeOnChangeWindow(){
        NotificationCenter.default.addObserver(self, selector: #selector(self.performChangeWindow), name: Notification.Name(K.changeWindowNotificationName), object: nil)
    }
    
    @objc func performChangeWindow() {
        self.window?.rootViewController = UIHostingController(rootView: SplashScreenView())
    }

However, I am not currently using SceneDelegate as I am initializing the app using WindowGroup

struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            SplashScreenView()
        }
    }
}

My question is : How can I perform the same thing I am doing using SceneDelegate now ?

1

There are 1 answers

0
el3ankaboot On BEST ANSWER

With the help of comments and some tutorials, I reached out to the solution (Tested on iOS 15, Xcode 13.2.1):

Add the following code to the Main App Launcher.

struct MyApp: App {
    
    @StateObject var appState = AppState.shared
      
    var body: some Scene {
        WindowGroup {
            SplashScreenView().id(appState.environment)
        }
    }
}

And then I created the AppState class, which is the class that when changes I will change the window.

class AppState: ObservableObject {
    static let shared = AppState()
    @Published var environment = "Production"
}

And whenever I wanted to change the environment and do the same functionality of changing window in UIKit , do the following :

AppState.shared.environment = "Pre-Production"