Sample CodevisionOSReviewed 2026-07-21View on Apple Developer

Working with generic spatial accessories

At a glance

Item Summary
Purpose Let people place digital replicas of a generic spatial accessory by tracking the accessory with ARKit.
App architecture WorkingWithGenericSpatialAccessoriesApp composes Window + WindowGroup + volumetric window + ImmersiveSpace around ContentView; AppModel coordinates ARKit provider updates and maps anchors into RealityKit content.
Main patterns SwiftUI scene composition, SwiftUI–RealityKit bridge, Explicit immersive-space lifecycle, Observable state owner, Provider session boundary, Async update consumer
Project style Code-rich sample with 12 scanned Swift file(s) and 1191 Swift line(s); resources and generated assets are excluded from those counts.

Project structure

Source bundle/
└── WorkingWithGenericSpatialAccessories/
    └── WorkingWithGenericSpatialAccessories/
        ├── Models/
        │   ├── AccessoryModel.swift  # AccessoryModel
        │   ├── AccessoryModel+Haptics.swift
        │   ├── AppModel.swift  # AppModel, ImmersiveSpaceState
        │   └── HapticModel.swift  # HapticModel, Constants
        ├── WorkingWithGenericSpatialAccessoriesApp.swift  # WorkingWithGenericSpatialAccessoriesApp
        └── Views/
            ├── ContentView.swift  # ContentView, AccessorySettingsForm
            ├── ImmersiveView.swift  # ImmersiveView
            └── VolumeView.swift  # VolumeView

Structure observations

  • The runtime boundary is Window + WindowGroup + volumetric window + ImmersiveSpace; the pruned tree lists only files that explain lifecycle, state, or framework integration.
  • App code is split into role-named views, models, managers, providers, components, or systems.

Overall architecture

Reference code

WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessoriesApp.swift:11 — the app or executable entry declares the outer scene lifecycle.

struct WorkingWithGenericSpatialAccessoriesApp: App {
    // ...
}

The diagram is a responsibility flow, not a claim that every adjacent node directly calls the next. It keeps scene ownership, shared state, RealityKit content, and framework-provider work at separate levels.

Ownership and state

Ownership evidence

WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessoriesApp.swift:12 — representative stored state or the nearest verified lifecycle anchor.

    @State private var appModel = AppModel()
Owner Object or state Relationship Mutation authority
WorkingWithGenericSpatialAccessoriesApp AppModel as appModel creates and retains Only the declaring scope writes
ContentView AppModel as appModel receives a shared/non-owning reference The upstream owner controls lifetime; this scope may invoke its mutable API
AccessoryModel ARKitSession as arkitSession creates and retains Only the declaring scope writes
ImmersiveSpaceState AccessoryModel as accessoryModel creates and retains Only the declaring scope writes

Ownership here is deliberately narrow: @Environment and weak references are shared links, initialized @State or stored services are lifecycle ownership, and a RealityView content closure owns additions to its entity graph without making the SwiftUI view a reference-type owner.

Class and protocol design

Type Responsibility Depends on or conforms to
WorkingWithGenericSpatialAccessoriesApp (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessoriesApp.swift:11) Declares app scenes and top-level dependency lifetime. App
ContentView (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/ContentView.swift:15) Presents UI and forwards gestures or lifecycle events. View
AppModel (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AppModel.swift:12) Owns observable feature state and domain transitions. Concrete framework collaborators
AccessoryModel (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:17) Owns observable feature state and domain transitions. Concrete framework collaborators
HapticModel (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/HapticModel.swift:12) Owns observable feature state and domain transitions. Concrete framework collaborators
ImmersiveView (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/ImmersiveView.swift:14) Presents UI and forwards gestures or lifecycle events. View
VolumeView (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/VolumeView.swift:12) Presents UI and forwards gestures or lifecycle events. View

The source defines no local substitution protocol in the reviewed boundary. Its protocol use is framework-facing (App, View, RealityKit/ARKit protocols, or platform adapters), so this document does not label the whole app protocol-oriented.

Access control

Symbol Access Verified effect Likely rationale
private(set) var accessoryTrackingProviderState: DataProviderState? (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:35) private(set) The getter keeps its wider visibility, while mutation stays inside the declaring type and its permitted same-file extensions. Inference: Protect a state invariant while allowing observation.
private let logger = Logger(category: "AccessoryModel") (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:19) private Use is restricted to the declaration and same-file extensions permitted by Swift. Inference: Hide implementation details and lifecycle-sensitive state.
internal var hapticModel: HapticModel? (WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:106) internal With no narrower modifier, Swift keeps the declaration module-internal. Inference: Allow app-target collaboration without exporting a library API.

No reviewed declaration uses fileprivate, public, open; unmodified Swift declarations are internal.

Reference code

WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:35 — representative visibility boundary.

    private(set) var accessoryTrackingProviderState: DataProviderState?
    private(set) var authorizationStatus: ARKitSession.AuthorizationStatus = .notDetermined {
        // ...
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
Scene declaration and dependency lifetime WorkingWithGenericSpatialAccessoriesApp The App/entry boundary determines window, volume, and immersive-space lifetime.
Presentation, attachments, and gestures ContentView SwiftUI view code forwards user intent and RealityView lifecycle events.
Shared feature state and commands AppModel A role-named owner prevents sibling views from duplicating transitions.
Tracking authorization and update streams WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:27 Provider lifetime and async updates remain outside render-only view code.

Design patterns

Pattern Source evidence Purpose or tradeoff
SwiftUI scene composition WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessoriesApp.swift:11 Keeps windows, volumes, and immersive-space lifecycle visible at the app boundary.
SwiftUI–RealityKit bridge WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/ImmersiveView.swift:28 Builds and updates a RealityKit entity graph from SwiftUI lifecycle closures.
Explicit immersive-space lifecycle WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessoriesApp.swift:13 Makes immersive presentation a scene transition rather than hidden global state.
Observable state owner WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AppModel.swift:12 Shares feature state across multiple views without moving framework resources into view values.
Provider session boundary WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:27 Owns provider lifetime separately from the SwiftUI view tree.
Async update consumer WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:146 Consumes provider or event streams in cancellable structured tasks.

Naming conventions

  • Role suffixes are evidence, not decoration: App: WorkingWithGenericSpatialAccessoriesApp; Model: AccessoryModel, AppModel, HapticModel; View: ContentView, ImmersiveView, VolumeView.
  • Protocols: no app-defined protocol in the reviewed source.
  • Commands use verb-led methods: makeAnchoringSource, toggleAccessoryLocation, initiateDigitalReplicaPlacement, queryLatestAccessoryAnchor, observeAccessoryTrackingProvider, observeAccessoryConnections, observeAccessoryConnectNotifications, observeAccessoryDisconnectNotifications.
  • Files generally match their primary type; Views, Models, Managers, Providers, Components, Systems, and Packages folders describe architectural roles where present.

Architecture takeaways

  • Treat WorkingWithGenericSpatialAccessoriesApp as the owner of scene declarations, not as the owner of every RealityKit entity created later.
  • Keep view-local interaction in SwiftUI, but move provider sessions, playback resources, shared game state, or transport state into a stable owner when their lifetime exceeds one render pass.
  • Run ARKit providers for the scene lifetime and consume their asynchronous updates in cancellable tasks; map anchors to entities at the boundary.
  • Model immersive-space open, transition, and close states explicitly so windows and immersive content cannot drift apart.

Source map

Source file Relevant symbols
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel.swift:17 AccessoryModel
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AccessoryModel+Haptics.swift:1 Feature implementation
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/AppModel.swift:12 AppModel, ImmersiveSpaceState
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessoriesApp.swift:11 WorkingWithGenericSpatialAccessoriesApp
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/ContentView.swift:15 ContentView, AccessorySettingsForm
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Models/HapticModel.swift:12 HapticModel, Constants
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/ImmersiveView.swift:14 ImmersiveView
WorkingWithGenericSpatialAccessories/WorkingWithGenericSpatialAccessories/Views/VolumeView.swift:12 VolumeView