Someone taps a harbor, opens its 3D model, and explores it. When they close the space, which harbor should the map remember? What if the model never opened?

Location Intelligence, part 4 of 4.

That round trip looks like a rendering feature. The parts that go wrong are about ownership. Which object holds the selected place while the scene is open? Who owns the downloaded model? What does the app show if the immersive space fails to open, if the person declines, or if they tap a different place while the first one is still loading?

The first three parts of this series kept location evidence separate from the claims an app makes. This last part applies the same separation to presentation: an immersive scene is one way of showing a place the app already understands, and the scene's lifetime is not the place's lifetime.

The journey lives outside the scene

The selected place, the saved itinerary, and the user's notes belong to the application. A RealityKit entity belongs to one rendered scene, and is destroyed with it.

So the scene receives an input, a stable place identifier and whatever it needs to draw, and the application keeps the source. The scene can then be torn down and rebuilt after a dismissal, a crash of the render process, or memory pressure, and nothing the user did is lost. A map annotation, a detail panel, and a 3D model can all represent the same place without sharing a mutable object.

The same structure is what makes the feature work on devices with no immersive presentation at all. On iPhone the "scene" is simply never created, and everything else is unchanged.

Opening is an operation with a result

The most common mistake in immersive code is setting a flag before asking:

SwiftGitHub
isImmersive = true
await openImmersiveSpace(id: "place")

openImmersiveSpace returns a result. The space may open, the person may cancel, or the system may refuse, for example because another immersive space is already open. In two of those three cases, the flag is now wrong, and the UI shows a "Close" button for a space that does not exist.

Model the lifecycle so the app's state follows what actually happened:

SwiftGitHub
import Foundation
import Observation

enum SpatialPresentation: Equatable, Sendable {
    case closed
    case opening(requestID: UUID, placeID: UUID)
    case open(sessionID: UUID, placeID: UUID)
    case closing(sessionID: UUID)
    case unavailable

    var placeID: UUID? {
        switch self {
        case .opening(_, let placeID), .open(_, let placeID): placeID
        case .closed, .closing, .unavailable: nil
        }
    }
}

enum OpenOutcome: Sendable {
    case opened
    case cancelled
    case failed
}

func resolveOpen(
    state: SpatialPresentation,
    requestID: UUID,
    outcome: OpenOutcome
) -> SpatialPresentation {
    guard case let .opening(currentID, placeID) = state,
          currentID == requestID else {
        return state
    }

    switch outcome {
    case .opened:
        return .open(sessionID: requestID, placeID: placeID)
    case .cancelled:
        return .closed
    case .failed:
        return .unavailable
    }
}

resolveOpen is a pure function, so every transition can be tested with no headset and no simulator. A result is applied only if the state is still .opening with the same request ID. A result for any other request leaves the state alone.

That guard has a limit worth being precise about. Ignoring an obsolete result does not undo what the system did. If an old request succeeded, an immersive space is open, whatever the state enum says. Declining to update a variable is not a dismissal. The physical state has to be reconciled by whoever issues the open and dismiss calls, which is the next section.

One owner for the effects

A person can tap "Explore" twice, or tap a second place while the first is opening. The system allows one immersive space at a time, so the app needs a policy: ignore the second request, or make the most recent selection win once the current transition settles. I prefer the second, and I want exactly one object issuing open and dismiss calls, in sequence:

SwiftGitHub
@MainActor
@Observable
final class SpatialCoordinator {
    private(set) var presentation: SpatialPresentation = .closed
    private(set) var isTransitioning = false
    private var desiredPlaceID: UUID?

    func show(
        placeID: UUID,
        open: (UUID) async -> OpenOutcome,
        dismiss: () async -> Void
    ) async {
        desiredPlaceID = placeID
        guard !isTransitioning else { return }
        isTransitioning = true
        defer { isTransitioning = false }

        while presentation.placeID != desiredPlaceID {
            if case let .open(sessionID, _) = presentation {
                presentation = .closing(sessionID: sessionID)
                await dismiss()
                presentation = .closed
                continue
            }
            guard let target = desiredPlaceID else { break }

            let requestID = UUID()
            presentation = .opening(requestID: requestID, placeID: target)
            let outcome = await open(target)
            presentation = resolveOpen(
                state: presentation, requestID: requestID, outcome: outcome
            )

            guard case .open = presentation else {
                desiredPlaceID = nil
                return
            }
        }
    }

    func close(dismiss: () async -> Void) async {
        desiredPlaceID = nil
        guard !isTransitioning, case let .open(sessionID, _) = presentation else {
            return
        }
        isTransitioning = true
        defer { isTransitioning = false }

        presentation = .closing(sessionID: sessionID)
        await dismiss()
        presentation = .closed
    }

    func spaceDidDisappear() {
        guard !isTransitioning else { return }
        desiredPlaceID = nil
        presentation = .closed
    }
}

A call to show while a transition is running records the new target and returns. The loop that is already running picks it up: when the first open resolves, it sees that the open place is not the desired one, dismisses, and opens the new target. However quickly the person taps, open and dismiss calls never overlap, and the final state matches the last thing they asked for. A close that arrives mid-transition works the same way: it clears the target, and the running loop dismisses the space once the open resolves, instead of leaving it on screen with nobody asking for it.

spaceDidDisappear handles the dismissal the app did not initiate. The system can close an immersive space when the person presses the Digital Crown or the app loses focus. The scene's content reports that it disappeared, and the coordinator returns to .closed. Without this, the state says .open indefinitely and the next "Explore" tap does nothing, because the app believes the place is already showing.

The coordinator takes open and dismiss as closures. That keeps SwiftUI's environment actions out of it and makes the whole sequence testable on any platform with two fake closures. The visionOS adapter is small:

SwiftGitHub
#if os(visionOS)
import SwiftUI

extension OpenOutcome {
    init(_ result: OpenImmersiveSpaceAction.Result) {
        switch result {
        case .opened: self = .opened
        case .userCancelled: self = .cancelled
        case .error: self = .failed
        @unknown default: self = .failed
        }
    }
}

struct ExploreButton: View {
    let placeID: UUID
    let coordinator: SpatialCoordinator

    @Environment(\.openImmersiveSpace) private var openImmersiveSpace
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace

    var body: some View {
        Button("Explore in 3D") {
            Task {
                await coordinator.show(
                    placeID: placeID,
                    open: { id in
                        OpenOutcome(await openImmersiveSpace(id: "place", value: id))
                    },
                    dismiss: { await dismissImmersiveSpace() }
                )
            }
        }
        .disabled(coordinator.presentation == .unavailable)
    }
}
#endif

The adapter's only job is to translate the framework's result into the domain's outcome. The ImmersiveSpace scene declared with the matching identifier receives the place ID as its value and calls coordinator.spaceDidDisappear() from its content's onDisappear.

This is the same split used for network requests elsewhere in an app. State records what the application believes, effects talk to a system whose answer has to be observed, and one owner serializes the effects.

Assets have three lifetimes

Loading a 3D model involves three things that are easy to treat as one:

  • the source bytes, a USDZ file downloaded or bundled, which can be cached on disk across launches;
  • the loaded resource, meshes and textures decoded into memory, which can be shared while the app is running;
  • the entity in a scene, which belongs to one hierarchy.

Each needs its own owner and eviction rule. A download can sensibly outlive the view that started it. GPU resources should not outlive the last scene using them by much. And an entity can have only one parent: adding the same entity to a second scene removes it from the first. To show a model in two places, load it once and clone(recursive:) it for each.

Selection changes interact with loading in the way described in every earlier part of this series. If the person picks place B while A's model is still loading, cancel A's load if possible, and when a load completes, check that it is still for the current place before attaching it. Otherwise harbor A's model appears in a scene titled with harbor B's name.

Geographic coordinates are not scene coordinates

Latitude and longitude are angles on a model of the Earth. A RealityKit transform is a position in meters relative to a parent entity, with x to the right, y up, and z toward the viewer. No universal function converts one to the other. For a tabletop model of a small area, you define the conversion by choosing an origin and a scale:

SwiftGitHub
struct TabletopFrame: Sendable {
    let originLatitude: Double
    let originLongitude: Double
    let realMetersPerSceneMeter: Double

    func scenePosition(latitude: Double, longitude: Double) -> SIMD3<Float> {
        let metersPerDegree = 111_195.0
        var deltaLongitude = longitude - originLongitude
        if deltaLongitude > 180 { deltaLongitude -= 360 }
        if deltaLongitude < -180 { deltaLongitude += 360 }

        let north = (latitude - originLatitude) * metersPerDegree
        let east = deltaLongitude * metersPerDegree
            * cos(originLatitude * .pi / 180)

        return SIMD3(
            Float(east / realMetersPerSceneMeter),
            0,
            Float(-north / realMetersPerSceneMeter)
        )
    }
}

This is a flat-Earth approximation around the origin. It is good to well under a meter over a harbor or a city district, and progressively worse over tens of kilometers, where a proper map projection is needed. North maps to negative z because, in RealityKit's convention, negative z points away from the viewer.

The scale is in the type's name for a reason. A USD file declares how many meters one of its units represents, and a model authored in centimeters and treated as meters arrives a hundred times too large. The first time the model appears inside the viewer's head or as a speck on the floor, check the units before the math.

Before adding gestures or animation, test the frame with known points. The origin lands at zero, a point 1 km north lands at the expected negative z, and a point 1 km east lands at the expected positive x.

Scale, comfort, and the fallback

A model that reads well at tabletop size can be uncomfortable at room size, and a control that is easy to reach at one scale is behind the viewer at another. Some rules I hold to:

  • never move the world around the viewer without their input; let them move the model;
  • make entering and leaving the immersive space predictable, and never automatic on selection;
  • keep text at a legible angular size and keep essential controls in a standard window;
  • do not require a precise physical gesture for something a button can do.

The map and the list remain first-class on a device that supports immersion. Some people will not want to enter an immersive space on a train or with limited mobility, or simply at that moment. A device being capable of immersion tells you nothing about what its user prefers.

Releasing the right things

When the scene goes away, release what belongs to it: animations, subscriptions to scene events, per-scene textures, and tasks started by its views. Keep what belongs to the application: the itinerary, the selection, and a download the app chose to cache.

The mirror-image mistake is keeping the render graph alive because the domain object is still in use. Write down each resource's owner and the event that frees it, then open and close the scene twenty times in a row while watching memory in Instruments. A leak of 30 MB per open is invisible in a demo and ends the session after a few minutes of real use.

Test the transition protocol

The pure transitions and the coordinator cover most of the risk and run on a Mac in milliseconds:

  • an obsolete result does not change the state;
  • cancel returns to .closed; failure goes to .unavailable;
  • show A, then show B while A is opening: the calls are open A, dismiss, open B, in that order, and the final state is B;
  • show the place that is already open: no calls at all;
  • close while A is opening: the calls are open A, then dismiss, and the final state is .closed;
  • system dismissal: state returns to .closed, and a later show works.

On hardware, test what a fake cannot reproduce: opening while another app's immersive space is active, the Digital Crown during loading, repeated open and close cycles under memory pressure, and returning to the map to find the same place selected. The simulator does not tell you whether the experience is comfortable.

The acceptance criterion for the whole feature is continuity. The place and the decisions the person made are the same before, during, and after the immersive scene.

What to ask of your own app

  • If the scene were destroyed right now, what user state would be lost?
  • Is any flag set before the open call returns?
  • How many objects can call open or dismiss, and can two calls overlap?
  • What updates the state when the system closes the space?
  • Where are the origin, scale, and units of the scene defined and tested?

Across these four parts the method has been the same. A map result, a photo's metadata, a model's label, and an immersive scene are each a source of evidence or a way of presenting it. The application's job is to keep hold of what it actually knows, and to be clear about which of those it is showing.

References

If this edition sharpened your next review, you can buy me a coffee.