> 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/map-creation.md).

# Map Creation

Scan a space into a new VPS map with the iOS SDK, with LiDAR or on any ARKit device: setup, scanning, drafts, background uploads and the API.

## Overview

From version 2.1.0 the iOS SDK can scan a space, package the capture, keep it on the device as a draft, and upload it to your account, where it is built into a VPS map. The capture format and the upload live inside the `MultiSetCore` framework. The package's `Sources/MultiSetSDK/Mapping/` supplies the ARKit side, and the [sample app](https://github.com/MultiSet-AI/multiset-swift-samples)'s `MultiSet-SDK-Samples/Views/Mapping/` the screens, which you can reuse.

There are two kinds of scan (`MappingCaptureKind`):

| Kind                    | Records                                       | Needs               | While scanning, the screen shows                       |
| ----------------------- | --------------------------------------------- | ------------------- | ------------------------------------------------------ |
| LiDAR (`.lidar`)        | Camera images, depth and a reconstructed mesh | A LiDAR scanner     | The reconstructed mesh                                 |
| Non-LiDAR (`.posedRGB`) | Camera images and their poses                 | World tracking only | ARKit's feature points, and how well tracking is going |

Both upload the same package layout; a Non-LiDAR package has no depth or mesh. Prefer LiDAR where the device has it. A Non-LiDAR map depends on good tracking, so scan textured, well-lit spaces and move slowly. The upload follows the [mobile map upload](https://docs.multiset.ai/fundamentals/rest-api-docs/map-upload/mobile-map-upload.md) format.

{% hint style="info" %}
Map creation needs only credentials, a client ID and secret or a [token provider](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/authentication.md#token-provider): a config without a map or object code is accepted. Scanning works before `initialize(config:callback:)`; uploading waits until the SDK is authenticated and starts by itself once it is.
{% endhint %}

***

## Setup

1. Add the `MultiSetSDK` product of the Swift package to your target. It includes `Mapping/` and its shaders. With a manual install, add the whole `Sources/MultiSetSDK` folder, and check that `Mapping/Coverage/ScanMeshSurface.metal` is under **Compile Sources**.
2. Forward the background upload session's wake-up from your app delegate, so an upload that finishes while your app is not running is recorded:

   ```swift
   func application(_ application: UIApplication,
                    handleEventsForBackgroundURLSession identifier: String,
                    completionHandler: @escaping () -> Void) {
       MultiSet.shared.mapping.handleEventsForBackgroundURLSession(
           identifier: identifier, completionHandler: completionHandler)
   }
   ```
3. Scans are recorded in landscape. Return the adapter's lock from your app delegate, or the scan screen rotates with the device. Outside the scan screen the lock answers with the orientations your `Info.plist` declares, so the rest of your app is unaffected:

   ```swift
   func application(_ application: UIApplication,
                    supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
       OrientationLock.shared.mask
   }
   ```
4. Call `await MultiSet.shared.mapping.resumeUploads()` when your app becomes active, for example from `sceneDidBecomeActive(_:)`.

The demo app's `AppDelegate.swift` and `SceneDelegate.swift` do all three. No background mode is needed. The camera and location usage descriptions in the [Info.plist configuration](https://docs.multiset.ai/native-sdk/ios-swift-native.md) cover scanning; without location access a scanned map carries no coordinates.

***

## Scanning

```swift
let source = ARMappingSource(kind: .lidar)        // or .posedRGB; owns the ARView, shown with MultiSetMappingARView
let mapping = MultiSet.shared.mapping

mapping.setSource(source)
await mapping.beginPreview()                      // camera on, nothing recorded; asks for camera access
await mapping.startScan()                         // tracking restarts; the scan's origin is here
// …the user walks the space…
let outcome = await mapping.stopScan()            // packages the scan
if outcome == .packaged {
    let draft = try mapping.saveDraft(named: "Lobby")
    await mapping.upload(draftID: draft.id)
}
mapping.endPreview()                              // when the screen goes away
```

Offer only the kinds in `MappingSupport.captureKinds`: both on a LiDAR device, `.posedRGB` alone without one. A `.lidar` source on a device without LiDAR previews, then fails at Start with `MappingFailure.Reason.sessionError` and a message saying why.

Scan rules the SDK enforces:

* A scan shorter than `MappingLimits.minimumScanDuration` (10 s) is discarded, and `stopScan()` returns `.discardedTooShort`. The SDK stops a scan at `MappingLimits.maximumScanDuration` (600 s) by itself.
* Starting needs about 1.5 GB of free space for a LiDAR scan and 600 MB for a Non-LiDAR scan.
* A map name must be at least `MappingLimits.minimumMapNameLength` (3) characters once trimmed.
* Frames too blurred to use are dropped; `scan.showsMotionWarning` turns on when the device moves too fast for a sharp capture.
* An interruption (a call, the app leaving the foreground) ends the scan, because tracking afterwards is in a different world frame. A scan past the minimum is packaged as it stood; a shorter one fails. `ARMappingSource` reports interruptions for you, and `scan.autoStopReason` says why the SDK stopped a scan by itself.

A Non-LiDAR scan adds:

* A frame is kept only when the camera has moved 5 cm or turned 5° since the last kept frame, and only once tracking has held for a second (two after a loss). Frames taken in the second before tracking is lost, or before ARKit corrects its pose in a jump, are deleted; `scan.discardedFrames` counts them.
* `scan.tracking` grades tracking (good, weak, lost) with the reason, and `scan.trackingAdvice` names a problem that has lasted, at most once every few seconds, for a toast.
* `scan.walkedArea` is the floor area the kept frames cover, once they span a metre.
* A warm device captures less often (`scan.isCapturingSlowly`). The scan stops by itself if free space falls below what packaging needs.
* Packaging can be stopped with `cancelPackaging()`; `resumePackaging()` starts it again and `discardScan()` deletes the scan.

***

## Observing

Read state from `MultiSet.shared.mapping` when one of these is posted on the main thread:

| Notification                       | Read                                                                                                                            |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `.multiSetMappingScanDidChange`    | `scan`: phase, elapsed time, packaging progress, frame counts, motion warning, and for Non-LiDAR the tracking status and advice |
| `.multiSetMappingDraftsDidChange`  | `drafts()`                                                                                                                      |
| `.multiSetMappingUploadsDidChange` | `uploadState(for:)`                                                                                                             |

A failed scan reports `MappingPhase.failed(MappingFailure)`, whose `message` is written for the user. Call `acknowledgeFailure()` once it has been shown. `MappingPhase` and the other mapping enums can gain cases, so a `switch` over them needs `@unknown default`.

***

## Drafts and Uploads

* **A draft stays until an upload succeeds.** Every failure keeps the scan, so a retry never costs another scan.
* **The transfer runs on a background `URLSession`.** It continues when the app is backgrounded, locked or terminated.
* **Uploads retry by themselves.** An interrupted upload waits 5, 15, 30, 60 and 120 s between attempts. After that it waits for `resumeUploads()` or for the network to return.
* **`deleteDraft(id:)` removes the scan's files** and cancels its upload.
* **Files location.** Scans are stored in Application Support, not in your app's Documents folder, so they do not appear in the Files app.
* **The map says how it was captured.** `MappingDraft.captureKind` tells the two kinds apart, and the map is created with the matching upload type.

***

## Custom Runtimes

To scan with something other than ARKit, implement `MultiSetMappingSource`.

* A `.lidar` source supplies raw camera frames (`MappingFrame`: a 1920 × 1440 `420f` image, a 256 × 192 `DepthFloat32` depth map, the camera transform and intrinsics, all from one frame), tracking samples, and the reconstructed mesh at stop.
* A `.posedRGB` source returns `.posedRGB` from `captureKind`, supplies `MappingRGBFrame` (a `420f` image at the size tracking started with, the transform, the intrinsics and the frame's timestamp) from `acquireRGBFrame()`, and passes every camera update to `MultiSet.shared.mapping.reportTrackingSample(_:)` with its tracking state, feature-point count and light estimate.

Pass every value raw; the SDK does every conversion. A frame of any other size is dropped. Call `reportSourceFailure(_:)` when your session fails, and `reportSourceInterrupted()` when it is interrupted. `Sources/MultiSetSDK/Mapping/ARMappingSource.swift` in the package is the reference implementation.

***

## API

```swift
MultiSet.shared.mapping: MultiSetMapping
mapping.setSource(_ source: MultiSetMappingSource?)
mapping.scan: MappingScanState
mapping.beginPreview() async
mapping.endPreview()
mapping.startScan() async
mapping.stopScan() async -> MappingStopOutcome
mapping.cancelPackaging()
mapping.resumePackaging() async -> MappingStopOutcome
mapping.discardScan() async
mapping.acknowledgeFailure()
mapping.saveDraft(named: String) throws -> MappingDraft
mapping.reportSourceFailure(_ message: String)
mapping.reportSourceInterrupted() async
mapping.reportTrackingSample(_ sample: MappingTrackingSample)
mapping.drafts() -> [MappingDraft]
mapping.deleteDraft(id: String)
mapping.upload(draftID: String) async
mapping.uploadState(for draftID: String) -> MappingUploadState?
mapping.dismissUploadFailure(for draftID: String)
mapping.hasActiveUploads: Bool
mapping.resumeUploads() async
mapping.handleEventsForBackgroundURLSession(identifier: String, completionHandler: @escaping () -> Void)
```

***

## Demo App Screens

| Screen                    | What it does                                                                                                                      |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Landing: **Mapping** card | Scans a space into a new map. On a LiDAR device it offers **LiDAR** or **Non-LiDAR**; on any other device it scans Non-LiDAR.     |
| `MappingInstructionsView` | Capture tips before a scan.                                                                                                       |
| `MappingFlowView`         | The landscape scan screen: start and stop, the scan mesh or feature points, tracking guidance, then naming, saving and uploading. |
| `DraftMapsView`           | Scans saved on the device and not yet uploaded, with their upload status.                                                         |

***

## Related

* [iOS SDK Overview](https://docs.multiset.ai/native-sdk/ios-swift-native.md)
* [Lifecycle and AR Runtimes](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/lifecycle-and-runtimes.md)
* [Mobile Map Upload](https://docs.multiset.ai/fundamentals/rest-api-docs/map-upload/mobile-map-upload.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/map-creation.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.
