2

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 ?

el3ankaboot
  • 302
  • 2
  • 12
  • 2
    You can use a .fullScreenCover to present a view controller – Timmy Jan 19 '22 at 14:51
  • Does this answer your question https://stackoverflow.com/a/70603447/12299030? – Asperi Jan 19 '22 at 14:53
  • Add environment variable and display contend depending on it. You are doing the same in the other places with SwiftUI, aren't you? – Cy-4AH Jan 19 '22 at 14:59
  • @NoeOnJupiter Thanks for your comment. I tried it and it worked. However I was wondering if this is the most efficient way to do so ? – el3ankaboot Jan 19 '22 at 15:13
  • @Asperi Thanks for your comment. Unfortunately, No. I am asking about how to add a covering window when a certain event happens. – el3ankaboot Jan 19 '22 at 15:14
  • @Cy-4AH Thanks for your comment. Can you please provide an example as I don't get exactly what you mean – el3ankaboot Jan 19 '22 at 15:14

1 Answers1

1

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"
el3ankaboot
  • 302
  • 2
  • 12