Anthony Harvey
Anthony Harvey

Reputation: 1

Detect that Immersive Space is dismissed

When the immersive space is dismissed by actions outside my app, how can I detect that happened and execute code based on that?

I need to be able to reset the scene and allow the user to relaunch the immersive space after they dismiss the scene by answering alerts from another app, or pressing the button on top of the headset. But I don't know how to detect that has occurred.

Upvotes: 0

Views: 421

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29271

You can use onDismiss

    ImmersiveSpace(id: "ImmersiveSpace") {
        ImmersiveView()
            .onDisappear {
                isShowingImmersive = false
            }
    }

or better yet scenePhase

struct ImmersiveView: View {
    @Environment(\.scenePhase) private var scenePhase
    @Binding var isShowingImmersive: Bool
    var body: some View {
        RealityView { content in
            // Add the initial RealityKit content
            if let scene = try? await Entity(named: "Immersive", in: realityKitContentBundle) {
                content.add(scene)
            }
        }.task(id: scenePhase) {
            switch scenePhase {
            case .inactive, .background:
                isShowingImmersive = false
            case .active:
                isShowingImmersive = true
            default:
                break
            }
        }
    }
}

You can use .task(id:) to do things when the Scene is being shown or not.

Upvotes: 1

Related Questions