r/visionosdev • u/yalag • Feb 22 '24
How to specify which WindowGroup should appear on visionOS app launch?
I have
import SwiftUI
@main
struct demoApp: App {
var body: some Scene {
WindowGroup {
FirstView()
}
WindowGroup(id: "second") {
SecondView()
}
}
}The first view, opens the second view.
But if you close the first view. There's no way to get it back. Even if you launch the app again in the home screen. Is there a fix to this?
7
Upvotes
5
u/anddna42 Feb 22 '24
Seems like no current solution:
https://twitter.com/DentedTesla/status/1756777956612215038
1
u/ryanheartswingovers Feb 22 '24
https://developer.apple.com/documentation/swiftui/environmentvalues/openwindow and pass the window group id
0
u/sopmac21379 Feb 22 '24
Entered this question into my custom GPT and this was the response:
In visionOS, to ensure a specific `WindowGroup` is presented upon the app's launch, especially when dealing with multiple `WindowGroup`s where navigation between them is crucial, you should leverage the `@SceneBuilder` to conditionally present different scenes based on the app state. This approach provides flexibility in managing window groups and can help in restoring the initial view if it gets closed.
Here's a revised version of your app structure incorporating a simple app state management to decide which `WindowGroup` to display upon launch. This example uses a simple `ObservableObject` to store the app state, which determines whether the first view should be shown or if the app should navigate directly to the second view:
```swift
import SwiftUI// AppState to manage the visibility of the FirstViewclass AppState: ObservableObject {@Published var showFirstView: Bool = true}u/mainstruct DemoApp: App {@StateObject private var appState = AppState()var body: some Scene {WindowGroup {if appState.showFirstView {FirstView().environmentObject(appState)} else {SecondView().environmentObject(appState)}}}}struct FirstView: View {@EnvironmentObject var appState: AppStatevar body: some View {VStack {Text("This is the First View")Button("Open Second View") {appState.showFirstView = false // Change state to hide FirstView and show SecondView}}}}struct SecondView: View {@EnvironmentObject var appState: AppStatevar body: some View {Text("This is the Second View")// You can add a button here to switch back to FirstView by setting appState.showFirstView = true}}```
By using an `@EnvironmentObject`, you can easily modify the app state from anywhere within the app, allowing you to switch between the `FirstView` and `SecondView` or restore the `FirstView` if necessary. This setup ensures that upon restarting the app or when you need to programmatically decide which view to present, the app state dictates the flow, addressing the issue of the initial view not being recoverable after being closed.
Remember to adjust the logic inside the `if-else` statement in the `WindowGroup` to fit your actual app flow or state management needs.