> For the complete documentation index, see [llms.txt](https://docs.multiset.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.multiset.ai/native-sdk/ios-swift-native/sample-views/arobjecttrackingview.md). Agents can also search and read this documentation through its [MCP server](https://docs.multiset.ai/~gitbook/mcp).

# ARObjectTrackingView

The iOS AR view that detects a registered object, draws an animated outline over it, shows each run's progress and re-tracks after a tracking break.

## Overview

The `ARObjectTrackingView` provides AR-based object tracking using the MultiSetSDK framework. This view captures frames from the AR camera and sends them to the MultiSet backend to detect and locate specific tracked objects, placing animated outline meshes over them in the real world.

## Description

The object tracking view handles:

* AR session management using ARKit and RealityKit
* Frame capture and processing for object detection
* Object tracking API requests (per configured `objectCodes`)
* Outline mesh rendering on detected objects, with a loading bar and a visibility toggle
* Run progress: the capture and server-wait overlays and the run status card
* Auto-tracking on view appearance
* Background re-tracking at configurable intervals
* Hiding outlines and re-tracking after a tracking break or a return from the background

## Key Features

### Auto-Tracking

When `MultiSetConfig.autoObjectTracking` is `true`, tracking starts automatically after the AR session reaches normal tracking state (with a 2-second initial delay and up to 30 seconds of polling).

### Background Re-Tracking

When `MultiSetConfig.backgroundObjectTracking` is `true`, the SDK periodically re-sends tracking requests to refine object positions at the interval specified by `bgObjectTrackingDurationSeconds`.

### Re-Tracking after a Tracking Break

Outlines are hidden while ARKit relocalizes after an interruption, the app sent to the background included, and shown again once it relocalizes. If a new world frame starts instead, each outline stays hidden until **that** object is tracked again. When `MultiSetConfig.restartObjectTracking` is `true`, the SDK re-tracks once tracking has been normal for 1 s, without reporting that run's miss. See [Tracked objects after a break](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/lifecycle-and-runtimes.md#tracked-objects-after-a-break).

### Capture Delay

`MultiSetConfig.objectTrackingCaptureDelay` adds a short pause before capturing the tracking frame. This gives the user time to aim the camera at the object after tapping Track. The capture overlay ("Hold steady on the object") covers that pause.

### Run Progress

A capture the user asked for covers the scene with `FrameCaptureOverlay`, then `ServerWaitOverlay` ("Uploading…", then "Finding the object…"). A background re-track reports on the `RunStatusCard` alone. Both overlays sit under the controls, so the close button and the card stay reachable.

### Outline Mesh Visualization

Each tracked object gets a thin animated purple outline, matching the MultiSet app, on iOS 16 and later: a two-layer RealityKit entity with a depth-only occlusion pass and the outline shader. Two objects whose meshes arrive together both render. `MeshLoadingBar` shows while an object mesh loads, and `MeshVisibilityToggle` hides or shows the outlines.

### Gizmo Management

The localization gizmo (RGB axes) is hidden on `onAppear` and restored on `onDisappear`, since object tracking operates independently from the localization anchor.

***

## SDK Methods Used

### Object Tracking Control

| Method                                  | Description                                                 |
| --------------------------------------- | ----------------------------------------------------------- |
| `MultiSet.shared.startObjectTracking()` | Triggers a tracking request for all configured object codes |
| `MultiSet.shared.stopObjectTracking()`  | Stops ongoing tracking                                      |
| `MultiSet.shared.clearObjectMeshes()`   | Removes all outline meshes from the scene                   |

### Gizmo Control

| Method                                   | Description                                         |
| ---------------------------------------- | --------------------------------------------------- |
| `MultiSet.shared.setGizmoVisible(false)` | Hides the localization gizmo during object tracking |

### State Properties

| Property                                         | Type                | Description                                                                       |
| ------------------------------------------------ | ------------------- | --------------------------------------------------------------------------------- |
| `MultiSet.shared.isObjectTrackingActive`         | `Bool`              | On from the moment a capture is requested; drives the Track button                |
| `MultiSet.shared.isShowingObjectTrackingOverlay` | `Bool`              | Like `isObjectTrackingActive`, without background re-tracking; drives the overlay |
| `MultiSet.shared.objectTrackingStage`            | `LocalizationStage` | The current run's stage                                                           |
| `MultiSet.shared.hasTrackedObject`               | `Bool`              | Whether tracking has succeeded at least once                                      |
| `MultiSet.shared.hasObjectMesh`                  | `Bool`              | Whether an object mesh is in the scene                                            |
| `MultiSet.shared.isObjectMeshLoading`            | `Bool`              | Whether an object mesh is being fetched or built                                  |
| `MultiSet.shared.config`                         | `MultiSetConfig?`   | Current SDK configuration                                                         |
| `MultiSet.shared.isAuthenticated`                | `Bool`              | Whether the SDK is authenticated                                                  |

***

## State Management

### View State Properties

| Property                         | Type                | Description                                                  |
| -------------------------------- | ------------------- | ------------------------------------------------------------ |
| `isTrackingNormal`               | `Bool`              | Whether AR tracking state is normal                          |
| `hasTrackedObject`               | `Bool`              | Whether an object has been successfully tracked              |
| `isObjectTrackingActive`         | `Bool`              | Polled from SDK, tracking request in progress                |
| `isShowingOverlay`               | `Bool`              | Polled from SDK, a capture the user asked for is in progress |
| `stage`                          | `LocalizationStage` | The current run's stage, from `onObjectTrackingStageChanged` |
| `hasObjectMesh`, `isMeshLoading` | `Bool`              | Polled from SDK, mesh in the scene and mesh loading          |
| `trackedObjectCode`              | `String`            | Code of the last successfully tracked object                 |
| `autoTrackingTask`               | `Task?`             | Reference to the auto-tracking polling task                  |
| `showCloseConfirmation`          | `Bool`              | Controls close confirmation alert                            |
| `showToast`                      | `Bool`              | Controls toast message visibility                            |
| `showFailureAlert`               | `Bool`              | Controls retry alert on failure                              |

***

## Callbacks

### onObjectTrackingStageChanged

Drives the overlays and the run status card:

```swift
sdkDelegate.onObjectTrackingStageChanged = { newStage, isBackground in
    stage = newStage
    isForegroundRun = newStage != .idle && !isBackground
    isShowingOverlay = MultiSet.shared.isShowingObjectTrackingOverlay
    runStatus.receive(RunStatusState(newStage))
}
```

### onObjectTrackingSuccess

Called when an object is successfully detected and positioned:

```swift
sdkDelegate.onObjectTrackingSuccess = { objectCode, confidence in
    runStatus.receive(.succeeded)
    trackedObjectCode = objectCode
    hasTrackedObject = true
    if MultiSet.shared.config?.showAlerts == true {
        showToastMessage("Object tracked", success: true)
    }
}
```

### onObjectTrackingFailure

Called when object detection fails. Shows a retry alert with a user-friendly message:

```swift
sdkDelegate.onObjectTrackingFailure = { error in
    runStatus.receive(.failed)
    if MultiSet.shared.config?.showAlerts == true {
        failureAlertMessage = userFriendlyTrackingMessage(for: error)
        showFailureAlert = true
    }
}
```

**User-friendly error mapping:**

| Server error             | Displayed message                            |
| ------------------------ | -------------------------------------------- |
| `"object not found"`     | Point the camera at the object and try again |
| `"low confidence"`       | Try a different angle or move closer         |
| `"api error"` / `"http"` | Check internet connection and try again      |

### onTrackingChanged

Handles AR tracking state changes to enable/disable the Track button:

```swift
sdkDelegate.onTrackingChanged = { state in
    isTrackingNormal = (state == .tracking)
}
```

### onObjectMeshLoaded

Called when the outline mesh for a tracked object has been downloaded and placed:

```swift
sdkDelegate.onObjectMeshLoaded = { objectCode in
    // Mesh is now visible in scene
}
```

***

## Actions

### startTracking()

Manually triggers object tracking:

```swift
private func startTracking() {
    MultiSet.shared.startObjectTracking()
}
```

### resetTracking()

Clears all tracked object meshes and resets state. Restarts auto-tracking if enabled:

```swift
private func resetTracking() {
    autoTrackingTask?.cancel()
    autoTrackingTask = nil
    MultiSet.shared.stopObjectTracking()
    MultiSet.shared.clearObjectMeshes()
    hasTrackedObject = false
    trackedObjectCode = ""
    showToastMessage("Tracking reset", success: true)
    startAutoTrackingIfNeeded()
}
```

### cleanup()

Cleans up resources when the view disappears:

```swift
private func cleanup() {
    autoTrackingTask?.cancel()
    autoTrackingTask = nil
    MultiSet.shared.stopObjectTracking()
}
```

***

## Configuration

The view reads object tracking settings from `MultiSet.shared.config`:

```swift
config.objectCodes = ["OBJ_CODE_1", "OBJ_CODE_2"]  // Objects to track (max 10)
config.autoObjectTracking = true                     // Auto-start tracking
config.backgroundObjectTracking = true               // Re-track at intervals
config.bgObjectTrackingDurationSeconds = 15.0        // Interval between re-tracks (5-30s)
config.restartObjectTracking = true                  // Re-track once tracking is back after a break
config.objectTrackingCaptureDelay = 1.0              // Delay before capture (0.5-3.0s)
config.firstObjectTrackingUntilSuccess = true        // Up to 5 silent retries of the first track
config.showAlerts = true                             // Show toast/alert feedback
```

## Overlay Components

### FrameCaptureOverlay

Shows during the capture delay of a capture the user asked for, with an object illustration and "Hold steady on the object".

### ServerWaitOverlay

Shows while the query is with the server:

* Semi-transparent black background
* Circular progress spinner
* "Uploading…", then "Finding the object…"

### RunStatusCard

A small card at the top left for every run, background re-tracks included, ending in a tick or a red mark.

***

## Related

* [LandingView](https://docs.multiset.ai/native-sdk/ios-swift-native/sample-views/landingview.md)
* [ARLocalizationView](https://docs.multiset.ai/native-sdk/ios-swift-native/sample-views/arlocalizationview.md)
* [MultiSetConfig](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/multisetconfig.md)
* [Lifecycle and AR Runtimes](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/lifecycle-and-runtimes.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.multiset.ai/native-sdk/ios-swift-native/sample-views/arobjecttrackingview.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
