Sample CodevisionOSReviewed 2026-11-01View on Apple Developer

Exploring object tracking with ARKit

At a glance

Item Summary
Purpose Find and track real-world objects in visionOS using reference objects you train with Create ML.
App architecture A SwiftUI app with two scenes: a plain WindowGroup that hosts HomeView and an ImmersiveSpace that hosts ObjectTrackingRealityView. One @Observable AppState is shared by both scenes. It owns the ARKitSession and a ReferenceObjectLoader. Per-anchor RealityKit content is built by ObjectAnchorVisualization.
Main patterns Actor isolation (@MainActor state owners under Swift 6 complete checking), Binding-based state propagation (@Bindable toggles and a custom Binding)
Project style One visionOS target. Folders by role: App/ (state and ARKit logic), Views/ (SwiftUI), Extensions/ (RealityKit entity helpers). Bundled .referenceobject files sit in Reference Objects/, and 3D-printable marker models in Printable Objects/.
Execution model AppState, ReferenceObjectLoader, ObjectAnchorVisualization, and the app are @MainActor. Long-running loops run in SwiftUI .task modifiers. Built-in objects load in a withTaskGroup. Button actions start plain Tasks.
State/event model Observation (@Observable) for app state, loader state, and a label text box. The ARKit events and anchorUpdates async sequences are consumed with for await.
Key frameworks/packages ARKit, RealityKit, SwiftUI, UniformTypeIdentifiers, UIKit (text mesh color). No package dependencies.

Project structure

Source bundle/
├── ObjectTracking/
│   ├── ObjectTrackingApp.swift          @main, two scenes
│   ├── App/
│   │   ├── AppState.swift               ARKitSession, provider, authorization, options
│   │   ├── ReferenceObjectLoader.swift  loads, enables, and removes reference objects
│   │   └── ObjectAnchorVisualization.swift  per-anchor entity tree and coordinate label
│   ├── Views/
│   │   ├── HomeView.swift               list, options, file importer, enter and exit
│   │   ├── ListEntryView.swift          per-object enable toggle
│   │   ├── ObjectTrackingRealityView.swift  immersive RealityView and anchor loop
│   │   └── InfoLabel.swift
│   └── Extensions/Entity+ObjectTracking.swift
├── Reference Objects/                   Apple_Magic_Keyboard.referenceobject, marker.referenceobject
├── Printable Objects/                   marker models (OBJ, STL)
└── ObjectTracking.xcodeproj/

Structure observations

  • App/ holds the non-view types. All three are @MainActor reference types, and two of them are @Observable.
  • The bundled .referenceobject files are target members (ObjectTracking.xcodeproj/project.pbxproj:255). ReferenceObjectLoader discovers them at run time by scanning the bundle’s resource folder for that extension (ObjectTracking/App/ReferenceObjectLoader.swift:52).
  • The target builds in Swift 6 with complete strict-concurrency checking and supports only visionOS (ObjectTracking.xcodeproj/project.pbxproj:426, ObjectTracking.xcodeproj/project.pbxproj:428).

Overall architecture

Reference code

ObjectTracking/ObjectTrackingApp.swift:17 — one state object feeds both scenes

@main
@MainActor
struct ObjectTrackingApp: App {
    @State private var appState = AppState()
    
    var body: some Scene {
        WindowGroup {
            HomeView(
                appState: appState,
                immersiveSpaceIdentifier: UIIdentifier.immersiveSpace
            )
            .frame(width: 1280, height: 720)
            .task {
                if appState.allRequiredProvidersAreSupported {
                    await appState.referenceObjectLoader.loadBuiltInReferenceObjects()
                }
            }
        }
        .windowStyle(.plain)
        .windowResizability(.contentSize)

        ImmersiveSpace(id: UIIdentifier.immersiveSpace) {
            ObjectTrackingRealityView(appState: appState)
        }
    }
}

Interpretation

The app struct is the composition root. It creates AppState once and passes it explicitly, not through the environment, to the window view and the immersive view. Both scenes therefore read and write the same observable instance. The window is the control surface: it lists objects, sets options, and enters or exits the space. The immersive view only starts tracking and renders anchors. ARKit access is behind AppState, and the views never touch ARKitSession directly.

Ownership and state

Ownership evidence

ObjectTracking/App/AppState.swift:31 — AppState owns the session and the current provider

@MainActor
@Observable
final class AppState {
    var isImmersiveSpaceOpened = false
    let referenceObjectLoader = ReferenceObjectLoader()
    // ...
    private let arkitSession = ARKitSession()
    
    private var objectTracking: ObjectTrackingProvider?
    
    private(set) var objectTrackingStartedRunning = false

    var providersStoppedWithError = false

    private(set) var worldSensingAuthorizationStatus = ARKitSession.AuthorizationStatus.notDetermined
    // ...
}
Owner Object or state Relationship Mutation authority
ObjectTrackingApp AppState Created in @State and passed to both scenes Shared. Views set isImmersiveSpaceOpened, the options, and providersStoppedWithError directly.
AppState ARKitSession private let, alive for the app’s lifetime; didLeaveImmersiveSpace() stops it (ObjectTracking/App/AppState.swift:25) AppState only
AppState ObjectTrackingProvider A new provider is created on every startTracking() and kept in private var objectTracking (ObjectTracking/App/AppState.swift:64) AppState only
AppState objectTrackingStartedRunning, worldSensingAuthorizationStatus private(set); written by the session-event loop and the authorization calls AppState
AppState ReferenceObjectLoader let, created with AppState Loader methods. Views also edit enabledReferenceObjects directly.
ReferenceObjectLoader referenceObjects, usdzsPerReferenceObjectID, progress private(set) collections and counters (ObjectTracking/App/ReferenceObjectLoader.swift:14) Loader
ObjectTrackingRealityView [UUID: ObjectAnchorVisualization] @State; filled on .added, removed on .removed, and cleared in onDisappear (ObjectTracking/Views/ObjectTrackingRealityView.swift:18) The view’s anchor loop
ObjectAnchorVisualization Entity tree, BoundingBoxOutline, MetricCoordinateLabel Builds them in init and updates them in update(with:) The visualization

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Main-actor isolation @MainActor @Observable final class AppState All app and ARKit state, including the session-event loop, is main-actor isolated. ObjectTracking/App/AppState.swift:10
Main-actor isolation @MainActor @Observable final class ReferenceObjectLoader Loader collections and progress counters are main-actor isolated. ObjectTracking/App/ReferenceObjectLoader.swift:11
Build setting SWIFT_STRICT_CONCURRENCY = complete, Swift 6 The compiler checks isolation crossings across the whole target. ObjectTracking.xcodeproj/project.pbxproj:428
Structured concurrency withTaskGroup + group.addTask One child task per bundled file awaits loadReferenceObject and then finishedOneFile. Both are main-actor methods, so each child hops to the main actor to touch loader state. A didStartLoading flag prevents a second load. ObjectTracking/App/ReferenceObjectLoader.swift:59
Shared-state safety Main-actor isolation with no await between append and sort After each await ReferenceObject(from:), the append, sort, and enable steps run without suspending. Concurrent loads therefore interleave only at the await points. ObjectTracking/App/ReferenceObjectLoader.swift:84
Long-running task .task { await appState.monitorSessionEvents() } for await over arkitSession.events, bound to HomeView’s .task lifetime. ObjectTracking/Views/HomeView.swift:154
Long-running task .task with for await anchorUpdate in objectTracking.anchorUpdates Bound to the immersive view’s .task. It starts tracking, then maintains the visualization dictionary. ObjectTracking/Views/ObjectTrackingRealityView.swift:29
Task creation Plain Task {} in button and onChange handlers Opening and dismissing the immersive space, file import, and authorization re-query run in unstored tasks that inherit the view’s main-actor context. ObjectTracking/Views/HomeView.swift:44

No DispatchQueue, lock, or Task.detached appears. Every mutable state owner relies on main-actor isolation.

Reference code

ObjectTracking/App/ReferenceObjectLoader.swift:59 — concurrent loads that report back through main-actor methods

    func loadBuiltInReferenceObjects() async {
        // Only allow one loading operation at any given time.
        guard !didStartLoading else { return }
        didStartLoading = true
        // ...
        await withTaskGroup(of: Void.self) { group in
            for file in referenceObjectFiles {
                let objectURL = Bundle.main.bundleURL.appending(path: file)
                group.addTask {
                    await self.loadReferenceObject(objectURL)
                    await self.finishedOneFile()
                }
            }
        }
    }

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
State propagation @Observable + @Bindable HomeView binds the “High frequency” and “Show coordinates” toggles directly to AppState properties. ObjectTracking/Views/HomeView.swift:183
State propagation Custom Binding ListEntryView maps a toggle to membership in enabledReferenceObjects. ObjectTracking/Views/ListEntryView.swift:16
State propagation onChange The immersive view pushes showsMetricCoordinateLabel into every live visualization. HomeView dismisses the space when a provider error flag or the authorization status changes. ObjectTracking/Views/ObjectTrackingRealityView.swift:55
State propagation Async sequence arkitSession.events drives objectTrackingStartedRunning, providersStoppedWithError, and the authorization status. ObjectTracking/App/AppState.swift:98
State propagation @Observable text box in a view attachment MetricCoordinateLabel writes text.value, and a SwiftUI view in a ViewAttachmentComponent redraws. ObjectTracking/App/ObjectAnchorVisualization.swift:148
Framework import ARKit ARKitSession, ObjectTrackingProvider, ReferenceObject. ObjectTracking/App/AppState.swift:8
Framework import RealityKit Entities, materials, RealityView, attachments. ObjectTracking/App/ObjectAnchorVisualization.swift:9
Framework import UniformTypeIdentifiers UTType for the reference-object file importer. ObjectTracking/Views/HomeView.swift:11
Framework import UIKit UIColor parameter for generated text meshes. ObjectTracking/Extensions/Entity+ObjectTracking.swift:9

Class and protocol design

Reference code

ObjectTracking/App/AppState.swift:41 — tracking start rebuilds reference objects with the current configuration, then runs a fresh provider

    func startTracking() async -> ObjectTrackingProvider? {
        // ...
        var configuration = ReferenceObject.Configuration()
        configuration.highFrameRateTrackingEnabled = highFrameRateTrackingEnabled
        var referenceObjects: [ReferenceObject] = []
        for object in referenceObjectLoader.enabledReferenceObjects {
            guard let url = object.inputFile else {
                referenceObjects.append(object)
                continue
            }
            do {
                let configuredObject = try await ReferenceObject(from: url, configuration: configuration)
                referenceObjects.append(configuredObject)
            } catch {
                print("Failed to apply configuration to \(object.name): \(error)")
                referenceObjects.append(object)
            }
        }

        // Run a new provider every time when entering the immersive space.
        let objectTracking = ObjectTrackingProvider(referenceObjects: referenceObjects)
        do {
            try await arkitSession.run([objectTracking])
        } catch {
            print("Error: \(error)")
            return nil
        }
        self.objectTracking = objectTracking
        return objectTracking
    }
Type Responsibility Depends on
ObjectTrackingApp Creates AppState, declares both scenes, and triggers built-in loading AppState
AppState Session, provider, authorization, app-wide options, and immersive-space flags ARKitSession, ReferenceObjectLoader
ReferenceObjectLoader Loads bundled or imported reference objects and their USDZ entities, tracks progress, and manages the enabled set ReferenceObject, Entity(contentsOf:)
HomeView Object list, options, file import, enter and exit controls, and authorization requests AppState
ObjectTrackingRealityView Starts tracking and maps anchor events to visualizations AppState, ObjectAnchorVisualization
ObjectAnchorVisualization Builds and updates one anchor’s wireframe or bounding box, axes, name, and coordinate label ObjectAnchor, RealityKit

No local protocol is declared. The types are concrete classes and structs, and the views receive their collaborators as stored properties.

Access control

Symbol Access Verified effect Likely rationale
AppState.arkitSession, objectTracking (ObjectTracking/App/AppState.swift:31) private Only AppState can run, stop, or replace the session’s provider. Inference: one owner for ARKit lifecycle.
objectTrackingStartedRunning, worldSensingAuthorizationStatus (ObjectTracking/App/AppState.swift:35) private(set) Views can observe these values but cannot write them. Inference: they reflect session facts, not UI choices.
providersStoppedWithError (ObjectTracking/App/AppState.swift:37) implicit internal HomeView resets it to false after it handles the error. Inference: a one-shot signal that the consumer acknowledges.
ReferenceObjectLoader.referenceObjects, usdzsPerReferenceObjectID, progress (ObjectTracking/App/ReferenceObjectLoader.swift:14) private(set) Only loader methods change the loaded set. Inference: keeps the list sorted and the counters consistent.
ReferenceObjectLoader.enabledReferenceObjects (ObjectTracking/App/ReferenceObjectLoader.swift:15) implicit internal ListEntryView appends and removes entries directly. Inference: the enabled set is user-editable selection state.
UIIdentifier (ObjectTracking/ObjectTrackingApp.swift:10) private enum The immersive-space ID constant is file-scoped. HomeView receives it as a parameter. Inference: one definition, passed in explicitly.
BoundingBoxOutline, MetricCoordinateLabel (ObjectTracking/App/ObjectAnchorVisualization.swift:76) private final class, nested Usable only inside ObjectAnchorVisualization. Inference: internal parts of one visualization.
MetricCoordinateText, MetricCoordinateLabelView (ObjectTracking/App/ObjectAnchorVisualization.swift:166) file private Shared only between the label and its attachment view in this file. Inference: keeps the view-attachment bridge local.

Reference code

ObjectTracking/App/ReferenceObjectLoader.swift:14 — read-only collections next to one writable selection

@MainActor
@Observable
final class ReferenceObjectLoader {
    private(set) var referenceObjects = [ReferenceObject]()
    var enabledReferenceObjects = [ReferenceObject]()
    var enabledReferenceObjectsCount: Int { enabledReferenceObjects.count }
    private(set) var usdzsPerReferenceObjectID = [UUID: Entity]()
    // ...
}

Logic ownership and placement

Logic Owning type or file Placement rationale
Authorization request, query, and change tracking AppState (ObjectTracking/App/AppState.swift:87) Next to the session that reports authorization events.
Provider configuration and run AppState.startTracking() Rebuilds each enabled object from its inputFile with the current high-frame-rate option. The loader’s copies keep the default configuration.
Leaving the space AppState.didLeaveImmersiveSpace() Stops the session and clears the flag. It is called from the window’s stop actions and from the immersive view’s onDisappear.
Reference-object loading and selection ReferenceObjectLoader Separates file I/O and progress from ARKit session state.
Anchor-to-entity mapping ObjectTrackingRealityView Keeps a per-anchor dictionary in view state for the space’s lifetime.
Entity construction and per-frame update ObjectAnchorVisualization Uses the trained USDZ as a wireframe when one is present. Otherwise it shows a bounding box.
Measurement label MetricCoordinateLabel (ObjectTracking/App/ObjectAnchorVisualization.swift:155) Reads the anchor’s uncorrected (correction: .none) coordinate space for metric display.

Design patterns

Pattern Source evidence Purpose or tradeoff
Actor isolation ObjectTracking/App/AppState.swift:10, ObjectTracking/App/ReferenceObjectLoader.swift:11 Main-actor classes protect all mutable state without locks. Concurrent loads hop back to the main actor to update it.
Binding-based state propagation ObjectTracking/Views/HomeView.swift:14, ObjectTracking/Views/ListEntryView.swift:16 Views write user choices straight into the observable owners. The tradeoff is that mutation authority over these fields is spread across views.

Main application flow

The flow below starts when a person taps “Start Tracking” and continues through the first anchor visualization.

Reference code

ObjectTracking/Views/HomeView.swift:45 — the window opens the space in an unstructured task

                            Button("Start Tracking \(appState.referenceObjectLoader.enabledReferenceObjectsCount) Object(s)") {
                                Task {
                                    switch await openImmersiveSpace(id: immersiveSpaceIdentifier) {
                                    // ...
                                    }
                                }
                            }

ObjectTracking/App/AppState.swift:66 — a new provider runs on the shared session

        let objectTracking = ObjectTrackingProvider(referenceObjects: referenceObjects)
        do {
            try await arkitSession.run([objectTracking])
        } catch {
            print("Error: \(error)")
            return nil
        }

ObjectTracking/Views/ObjectTrackingRealityView.swift:40 — the immersive view’s task consumes anchor updates

        .task {
            guard let objectTracking = await appState.startTracking() else { return }
            // ...
            for await anchorUpdate in objectTracking.anchorUpdates {
                let anchor = anchorUpdate.anchor
                let id = anchor.id

                switch anchorUpdate.event {
                case .added:
                    // ...
                    let model = appState.referenceObjectLoader.usdzsPerReferenceObjectID[anchor.referenceObject.id]
                    let visualization = ObjectAnchorVisualization(
                        for: anchor,
                        withModel: model,
                        showsMetricCoordinateLabel: appState.showsMetricCoordinateLabel
                    )
                    self.objectVisualizations[id] = visualization
                    root.addChild(visualization.entity)
                case .updated:
                    objectVisualizations[id]?.update(with: anchor)
                case .removed:
                    objectVisualizations[id]?.entity.removeFromParent()
                    objectVisualizations.removeValue(forKey: id)
                }
            }
        }

Naming conventions

  • Types: role suffixes that match behavior. …State is the observable app owner, …Loader loads resources, …Visualization builds entities for an anchor, and …View is a SwiftUI view.
  • State flags: Boolean names read as facts (isImmersiveSpaceOpened, objectTrackingStartedRunning, providersStoppedWithError, canEnterImmersiveSpace, allRequiredProvidersAreSupported).
  • Methods: verbs for commands (startTracking, requestWorldSensingAuthorization, queryWorldSensingAuthorization), monitor… for long-running loops, and did… for event notifications from views (didLeaveImmersiveSpace).
  • Files and extensions: one primary type per file. Entity helpers live in Entity+ObjectTracking.swift.

Architecture takeaways

  • One observable owner, created at the app root and passed explicitly to both scenes, keeps window and immersive-space state consistent without environment lookups.
  • The ARKit session lives for the whole app, but a new provider is created on each entry. Stopping on exit keeps the provider lifecycle aligned with the immersive space.
  • Configuration that can change between runs (high frame rate) is applied at session start by reloading from each object’s URL, so the app does not keep several configured copies in memory.
  • Main-actor classes and a task group give concurrent file loading without locks. Correctness depends on keeping each state update free of suspension points.
  • View-owned @State dictionaries keyed by anchor ID are enough to manage RealityKit content lifetimes inside one immersive view.

Source map

Source file Relevant symbols
ObjectTracking/ObjectTrackingApp.swift ObjectTrackingApp, UIIdentifier
ObjectTracking/App/AppState.swift AppState, startTracking, didLeaveImmersiveSpace, monitorSessionEvents, requestWorldSensingAuthorization
ObjectTracking/App/ReferenceObjectLoader.swift ReferenceObjectLoader, loadBuiltInReferenceObjects, loadReferenceObject, addReferenceObject
ObjectTracking/App/ObjectAnchorVisualization.swift ObjectAnchorVisualization, BoundingBoxOutline, MetricCoordinateLabel, MetricCoordinateText
ObjectTracking/Views/HomeView.swift HomeView, referenceObjectList
ObjectTracking/Views/ListEntryView.swift ListEntryView
ObjectTracking/Views/ObjectTrackingRealityView.swift ObjectTrackingRealityView
ObjectTracking/Extensions/Entity+ObjectTracking.swift createText, createAxes, applyMaterialRecursively
ObjectTracking.xcodeproj/project.pbxproj Strict concurrency, bundled reference objects