> 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/api-reference/lifecycle-and-runtimes.md).

# Lifecycle and AR Runtimes

How the iOS SDK retries, refreshes and recovers after a tracking break, how to show a run's progress, threading rules, and driving the SDK from your own ARView or another AR runtime.

## Overview

`MultiSet.shared` runs the whole localization and object tracking loop: the first fix and its silent retries, background refreshes, and recovery after AR tracking breaks. This page explains each of them, how to show a run's progress, and how to connect the SDK to an `ARView` you create yourself or to an AR runtime other than ARKit.

{% hint style="info" %}
The ARKit and RealityKit code is the package's AR adapter (`Sources/MultiSetSDK/` in [multiset-swift-package](https://github.com/MultiSet-AI/multiset-swift-package)), part of the `MultiSetSDK` product. `MultiSetARView`, `setARSession`, `setMeshVisible` and the other ARKit calls on this page come from the adapter; the `MultiSetCore` framework itself has no ARKit dependency.
{% endhint %}

***

## Retries, Refreshes and Tracking Recovery

### First fix

With `firstLocalizationUntilSuccess` (default on), a failed first localization is retried silently up to **5 times** before `onLocalizationFailure` reports it. A retry follows 0.5 s after a miss, or 4 s, 8 s and then 12 s after a timeout or a server error, so a busy server is not asked twice at once. `isLocalizing` and `isShowingOverlay` stay `true` through each wait, and `localize()` is refused meanwhile.

The rule covers the first fix of each session: after `initialize`, after `resetSession()`, and each time a new AR view attaches. `firstObjectTrackingUntilSuccess` follows the same rule for the first tracked object.

### Background refresh

With `backgroundLocalization` on, the next refresh is armed after every run, `bgLocalizationDurationSeconds` later. Switching it through `updateConfig(_:)` takes effect at once: on after a fix arms a refresh, off cancels the one armed. A missed refresh is reported through `onLocalizationFailure` and waits the full interval before the next.

### Recovery after a tracking break

With `relocalization` (default on), a break after a fix is recovered without a tap. The SDK waits for normal tracking, lets it settle for 1 s, then re-localizes, and retries every second until a fix lands. Recovery runs show no overlay and never call `onLocalizationFailure`; the fix that lands calls `onLocalizationSuccess` as usual. Nothing is recovered before the first fix. With `relocalization` off, the last fix stays applied and only a tap or a background refresh corrects it.

| Break                                                               | Scene out of place |
| ------------------------------------------------------------------- | ------------------ |
| Session interrupted, app sent to the background, ARKit relocalizing | At once            |
| A new world frame (`notifyWorldOriginReset()`)                      | At once            |
| Any other limited tracking (fast motion, too little detail)         | After 2 s          |

While the scene is out of place, content placed in the map frame sits where the room no longer is. The SDK hides the map mesh for that time through `MultiSetMeshRenderer.setMapMeshVisible(_:)`, which `MultiSetARView` implements apart from `setMeshVisible(_:)`, so neither undoes the other. Hide your own content until the recovery lands:

```swift
func onRecoveryPhaseChanged(_ phase: RecoveryPhase, needsRealignment: Bool) {
    contentRoot.isEnabled = !needsRealignment
    switch phase {
    case .none: statusLabel.text = nil
    case .waitingForTracking: statusLabel.text = "Waiting for tracking…"
    case .realigning: statusLabel.text = "Re-aligning scene…"
    }
}
```

`MultiSet.shared.recoveryPhase` and `MultiSet.shared.needsRealignment` hold the same state.

`MultiSet.shared.mapAlignment` and `geoAlignment` are cleared for the same time, and their availability reports `.needsRealignment`. See [Polling API](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/polling-api.md#availability).

### Returning from the background

`MultiSetARView` starts a fresh world frame when the app returns from the background, instead of resuming the old one, and re-localizes and re-tracks in it once ARKit tracks normally. After the device was carried somewhere else, the old world frame no longer matches the room, so a fix made in it would be moved off again.

### Tracked objects after a break

Object outlines are hidden while ARKit relocalizes after an interruption (the app sent to the background included), and shown again once it relocalizes. If it cannot and a new world frame starts, each outline stays hidden until **that** object is tracked again. With `restartObjectTracking` (default on), the SDK re-tracks once tracking has been normal for 1 s; a miss from that run is not reported.

***

## Showing a Run's Progress

Each localization and object tracking run reports where it stands. `onLocalizationStageChanged(_:isBackground:)` and `onObjectTrackingStageChanged(_:isBackground:)` (both optional) fire on every change:

| Stage                            | Meaning                                                                                          |
| -------------------------------- | ------------------------------------------------------------------------------------------------ |
| `.capturing(captured:required:)` | Frames are being taken. For object tracking this covers `objectTrackingCaptureDelay`.            |
| `.uploading`                     | The query is going out. A fixed step of up to 2 s, since the request reports no progress.        |
| `.awaitingResponse`              | The query is sent and the server is searching.                                                   |
| `.idle`                          | The run ended. Its result arrives through the usual success, failure or false-positive callback. |

`isBackground` is `true` for a background refresh, a recovery, a background re-track and a restart after a tracking loss: show those without covering the scene. A run that is retried silently goes back to `.idle` between attempts while `isShowingOverlay` stays `true`.

```swift
func onLocalizationStageChanged(_ stage: LocalizationStage, isBackground: Bool) {
    switch stage {
    case .capturing(let captured, let required): statusLabel.text = "Capturing \(captured) of \(required)"
    case .uploading: statusLabel.text = "Uploading…"
    case .awaitingResponse: statusLabel.text = "Matching against the map…"
    case .idle: statusLabel.text = nil
    @unknown default: statusLabel.text = nil
    }
}
```

`LocalizationStage` may gain cases in a later release, so a `switch` over it needs `@unknown default`. `MultiSet.shared.localizationStage` and `objectTrackingStage` hold the same state.

A mesh arrives after the fix that asked for it. `MultiSet.shared.isMapMeshLoading` and `isObjectMeshLoading` (from the AR adapter) are `true` from the moment it is fetched until it is in the AR scene; the framework's own `isLoadingMapMesh` and `isLoadingObjectMesh` cover the fetch alone. A fix on a map whose mesh is already in the scene does not turn them on.

### State properties

| Property                                               | Description                                                                                       |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| `isLocalizing`                                         | A localization run is in progress or a silent retry is due                                        |
| `isShowingOverlay`                                     | A run the user is waiting on is in progress: cover the scene                                      |
| `isCapturingFrames`                                    | Frames are being captured                                                                         |
| `localizationStage`                                    | The current localization run's stage                                                              |
| `hasLocalized`                                         | A fix has been accepted in this session                                                           |
| `recoveryPhase`, `needsRealignment`                    | Recovery after a tracking break                                                                   |
| `isObjectTrackingActive`                               | An object tracking run is requested or in progress: drive the capture button from it              |
| `isShowingObjectTrackingOverlay`                       | Like `isObjectTrackingActive`, without background re-tracking: drive a progress indicator from it |
| `objectTrackingStage`                                  | The current object tracking run's stage                                                           |
| `hasTrackedObject`                                     | An object has been tracked in this session                                                        |
| `anchorTrust`                                          | Standing of the pose consistency anchor                                                           |
| `watermarkClearance`                                   | Height the watermark occupies at the bottom left; lift your bottom-left controls by it            |
| `mapAlignment`, `geoAlignment`                         | Where the map sits in the AR session, and the session on Earth                                    |
| `mapAlignmentAvailability`, `geoAlignmentAvailability` | Whether each alignment can be used, and why not                                                   |

[Polling API](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/polling-api.md) lists every value you can read at any time, including the alignment, the conversions between the AR session, the map and Earth, and the device's live position. The alignment calls are available from iOS SDK 2.4.0 and above.

***

## Threading

`MultiSet` and `MultiSetCallback` are isolated to the main actor.

* **Callbacks.** Every `MultiSetCallback` method is called on the main thread. Update UI and `@Published` state directly; there is no need for `DispatchQueue.main.async`.
* **Calling the SDK.** Call `MultiSet.shared` from the main thread. SwiftUI views and UIKit view controllers already run there. From a background task, `await` the call, as in `await MultiSet.shared.localize()`.
* **Adopting the callback.** A class that adopts `MultiSetCallback` in its declaration is inferred `@MainActor`, so create it on the main thread. `@StateObject` and `@ObservedObject` already do.
* **Blocking work.** Network requests and mesh file reads and writes run off the main thread. The AR adapter's mesh renderers also parse GLBs off the main thread, so the AR view keeps rendering while a mesh loads.

***

## Using Your Own ARView

With the `MultiSetSDK` product (the AR adapter) in your target, the SDK attaches to an `ARView` you create yourself:

```swift
MultiSet.shared.setARSession(arView.session)
MultiSet.shared.setParentEntity(mapAnchor)                 // map meshes are parented here
MultiSet.shared.setObjectTrackingRootEntity(objectAnchor)  // object meshes, world-fixed
MultiSet.shared.setGizmoUpdateHandler { position, rotation in
    mapAnchor.transform.translation = position
    mapAnchor.transform.rotation = rotation
}
```

Call these after `initialize(config:callback:)`. The SDK moves nothing itself on this path; your handler moves `mapAnchor`. Call `MultiSet.shared.setARSession(nil)` when your `ARView` goes away; the SDK shows its watermark for as long as a session is attached.

If your app sets its own `ARSessionDelegate`, forward tracking from it, or interruption and relocalization stop reaching the SDK: call `MultiSet.shared.forwardARTrackingState(camera.trackingState)` in `session(_:cameraDidChangeTrackingState:)`, and `MultiSet.shared.notifyTrackingInterrupted()` in `sessionWasInterrupted(_:)` and `sessionInterruptionEnded(_:)`.

When your app moves to the background, pause the session and call `forwardARTrackingState(.notAvailable)`. When it returns:

1. Start a fresh world frame with `run(_:options: [.resetTracking, .removeExistingAnchors])` and call `notifyWorldOriginReset()`. The SDK re-localizes and re-tracks in it once ARKit tracks normally.
2. Create the `ARView` with `automaticallyConfigureSession: false`, so RealityKit does not resume the old frame for you.
3. Do not capture `currentFrame` until a frame newer than the trip arrives.
4. Return `false` from `sessionShouldAttemptRelocalization(_:)` (the default), so ARKit never fits the old frame back on after an interruption.

`Sources/MultiSetSDK/Session/ARSessionController.swift` and `ARSessionFrameSource.swift` in the package show all of this.

***

## Custom AR Runtimes

The `MultiSetCore` framework has no ARKit dependency. To drive it from another runtime, link only the package's `MultiSetCore` product and `import MultiSetCore`. Then implement `MultiSetFrameSource` and attach it after `initialize(config:callback:)`:

```swift
final class MyFrameSource: MultiSetFrameSource {
    @MainActor func acquireFrame() async -> CameraFrame? {
        // Build a CameraFrame from the raw camera image, camera-to-world transform, intrinsics,
        // interface orientation and monotonic timestamp. Do not correct for portrait.
        return nil
    }

    var isHostActive: Bool {
        true
    }

    @MainActor func resetWorldOrigin() {
        // Restart your tracker from a fresh world origin. Optional: the default is a no-op.
    }
}

MultiSet.shared.setFrameSource(MyFrameSource())
```

Detach it with `setFrameSource(nil)` when your AR screen closes. The watermark stays up for as long as a frame source is attached.

* **Conventions.** Poses are right-handed, +Y up and gravity-aligned, with the camera looking down −Z, in metres. `timestamp` must come from a monotonic clock, never `Date()`.
* **Foreground.** Return `false` from `isHostActive` while your app is not in the foreground. Scheduled localization and re-tracking wait for it rather than capturing in the background.
* **Reset.** Implement `resetWorldOrigin()` wherever your tracker can restart. Without it, `resetSession()` drops everything the SDK holds but leaves the world frame the discarded pose was measured in.
* **Tracking signals.** Report `notifyTrackingInterrupted()` for a recoverable loss, `notifyWorldOriginReset()` when the world frame is replaced, and `reportTrackingState(_:)` for every tracking-quality change. A recovery after a break starts only when `reportTrackingState(.tracking)` follows it. Report a trip to the background as an interruption too, and the tracking state again once frames resume. `Sources/MultiSetSDK/Session/ARTrackingSignals.swift` shows the ARKit mapping.
* **Optional receivers.** Attach a `MultiSetPoseSink` for accepted poses, a `MultiSetMeshRenderer` to draw the downloaded GLB meshes (implement its optional `setMapMeshVisible(_:)` to hide the map mesh while the scene is out of place), and a `MultiSetGeoHintProvider` to supply GPS for `passGeoPose`. Meshes are not downloaded while no renderer is attached.
* **Device position.** `deviceGeolocation()` and `deviceMapPose()` come from the AR adapter. On your own runtime, pass the raw camera transform and the interface orientation to `GeoAlignment.geolocation(ofCamera:orientation:headingMode:)` and `MapAlignment.mapPose(ofCamera:orientation:)`. See [Polling API](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/polling-api.md#device-position).
* **Geo-hint altitude.** The API expects heights above the WGS84 ellipsoid, not mean sea level. From CoreLocation, pass `ellipsoidalAltitude` rather than `altitude`. Pass `nil` when `verticalAccuracy` is negative: the SDK then sends latitude and longitude only, with `use2DFiltering` on for that request.

***

## Related

* [MultiSetConfig](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/multisetconfig.md)
* [MultiSetCallback](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/multisetcallback.md)
* [Polling API](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/polling-api.md)
* [Map Creation](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/map-creation.md)
* [iOS SDK Overview](https://docs.multiset.ai/native-sdk/ios-swift-native.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/api-reference/lifecycle-and-runtimes.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.
