Sample CodeiOS, iPadOSReviewed 2026-11-01View on Apple Developer

Saving and loading world data

At a glance

Item Summary
Purpose Persist an ARWorldMap (with a placed virtual object and a camera snapshot) to disk, then reload it so ARKit relocalizes and restores the object in the same physical place.
App architecture A single-scene UIKit app. AppDelegate returns the scene configuration and SceneDelegate adopts the storyboard window. One ViewController is the ARSCNView and ARSession delegate and owns the whole feature: placement, mapping-status UI, save, load, and reset.
Main patterns Delegate or data-source callbacks (ARSCNViewDelegate, ARSessionDelegate, plus UIKit lifecycle delegates)
Project style One app target with a flat ARPersistence/ folder: lifecycle delegates, one view controller, a custom ARAnchor subclass, a utilities file of extensions, and a button subclass.
Execution model UIKit lifecycle, IB actions, and ARKit delegate callbacks. The world-map completion handler hops to DispatchQueue.main for button updates; alerts are presented through DispatchQueue.main.async. No Swift concurrency appears.
State/event model ARKit delegate callbacks drive UI state (worldMappingStatus, tracking state); the controller stores a small amount of mutable state (virtualObjectAnchor, isRelocalizingMap); the saved map file is the only persistent state.
Key frameworks/packages Swift modules UIKit, SceneKit, ARKit, simd; no packages.

Project structure

ARPersistence.xcodeproj          # 1 iOS app target
ARPersistence/
├── AppDelegate.swift            # @UIApplicationMain, scene configuration
├── SceneDelegate.swift          # UIWindowSceneDelegate (storyboard window)
├── ViewController.swift         # delegates, placement, save/load/reset
├── SnapshotAnchor.swift         # ARAnchor subclass carrying JPEG data (NSSecureCoding)
├── Utilities.swift              # status descriptions, feedback text, showAlert, orientation
├── RoundedButton.swift          # @IBDesignable button
├── Base.lproj/Main.storyboard   # ARSCNView, buttons, labels, tap gesture
└── Info.plist                   # scene manifest, camera usage

Structure observations

  • The project has one application target (ARPersistence.xcodeproj/project.pbxproj:123) for device families 1,2 (ARPersistence.xcodeproj/project.pbxproj:335) with an iOS 15 deployment target (ARPersistence.xcodeproj/project.pbxproj:328).
  • ViewController.swift is grouped by // MARK: sections (IBOutlets, View Life Cycle, ARSCNViewDelegate, ARSessionDelegate, ARSessionObserver, Persistence, AR session management, Placing AR Content) rather than by separate types (ARPersistence/ViewController.swift:73, ARPersistence/ViewController.swift:151).
  • The one model type is SnapshotAnchor, a custom anchor that rides inside the world map so the snapshot is saved and restored with it (ARPersistence/SnapshotAnchor.swift:10).
  • The storyboard wires the ARSCNView delegate to the controller (ARPersistence/Base.lproj/Main.storyboard:21) and connects the save, load, reset, and tap actions (ARPersistence/Base.lproj/Main.storyboard:43, ARPersistence/Base.lproj/Main.storyboard:34, ARPersistence/Base.lproj/Main.storyboard:92, ARPersistence/Base.lproj/Main.storyboard:165). Info.plist names SceneDelegate and the Main storyboard for the default scene (ARPersistence/Info.plist:38).

Overall architecture

Reference code

ARPersistence/ViewController.swift:165 — save: capture the map, add a snapshot anchor, archive securely, write atomically

    @IBAction func saveExperience(_ button: UIButton) {
        sceneView.session.getCurrentWorldMap { worldMap, error in
            guard let map = worldMap
            else { self.showAlert(title: "Can't get current world map", message: error!.localizedDescription); return }
            
            // Add a snapshot image indicating where the map was captured.
            guard let snapshotAnchor = SnapshotAnchor(capturing: self.sceneView)
            else { fatalError("Can't take snapshot") }
            map.anchors.append(snapshotAnchor)
            
            do {
                let data = try NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true)
                try data.write(to: self.mapSaveURL, options: [.atomic])
                DispatchQueue.main.async {
                    self.loadExperienceButton.isHidden = false
                    self.loadExperienceButton.isEnabled = true
                }
            } catch {
                fatalError("Can't save map: \(error.localizedDescription)")
            }
        }
    }

ARPersistence/ViewController.swift:216 — load: pull the snapshot out, then run with initialWorldMap

        worldMap.anchors.removeAll(where: { $0 is SnapshotAnchor })
        
                let configuration = self.defaultConfiguration // this app's standard world tracking settings
        configuration.initialWorldMap = worldMap
        sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
        
        isRelocalizingMap = true
        virtualObjectAnchor = nil

Interpretation

Observed: the virtual object is never serialized as geometry. It is represented by a named ARAnchor ("virtualObject") that ARKit saves inside the world map. When the map relocalizes, ARKit re-adds that anchor and renderer(_:didAdd:for:) attaches the SceneKit node to it (ARPersistence/ViewController.swift:75, ARPersistence/ViewController.swift:83). The snapshot travels the same way, as a SnapshotAnchor, and is removed again before the map is run (ARPersistence/ViewController.swift:216).

Inference: anchors are the persistence unit. Anything the app needs to restore spatially is attached to an anchor with a stable name or subclass, and the app’s content is rebuilt from anchors on relocalization.

Ownership and state

Ownership evidence

ARPersistence/ViewController.swift:297 — the controller stores the placed anchor and the shared SceneKit node

    var virtualObjectAnchor: ARAnchor?
    let virtualObjectAnchorName = "virtualObject"

    var virtualObject: SCNNode = {
        guard let sceneURL = Bundle.main.url(forResource: "cup", withExtension: "scn", subdirectory: "Assets.scnassets/cup"),
            let referenceNode = SCNReferenceNode(url: sceneURL) else {
                fatalError("can't load virtual object")
        }
        referenceNode.load()
        
        return referenceNode
    }()
Owner Object or state Relationship Mutation authority
Storyboard ARSCNView, buttons, labels, thumbnail Instantiated by Interface Builder; held by weak outlets (ARPersistence/ViewController.swift:15 through ARPersistence/ViewController.swift:21) View hierarchy retains them
ViewController virtualObjectAnchor: ARAnchor? Stored var (ARPersistence/ViewController.swift:297) handleSceneTap(_:) replaces it; renderer(_:didAdd:for:) restores it after relocalization; loadExperience(_:) and resetTracking(_:) clear it
ViewController isRelocalizingMap Stored var (ARPersistence/ViewController.swift:228) Set by loadExperience(_:), cleared by resetTracking(_:); gates tapping and the relocalization prompt
ViewController virtualObject: SCNNode Created once by a property initializer and re-parented to whichever node the anchor gets renderer(_:didAdd:for:)
ViewController mapSaveURL lazy var in the Documents directory (ARPersistence/ViewController.swift:152) Read by save and by mapDataFromFile
ARSession Anchors, world map, tracking state Owned by the ARSCNView’s session; ViewController sets itself as delegate (ARPersistence/ViewController.swift:55) ARKit, plus add(anchor:)/remove(anchor:) from the controller
SnapshotAnchor imageData Immutable let (ARPersistence/SnapshotAnchor.swift:12) Set in initializers only

defaultConfiguration is a computed property that builds a new ARWorldTrackingConfiguration each time (ARPersistence/ViewController.swift:230), so reset and load always start from the same settings.

Concurrency, scheduling, and thread safety

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

Concern Source mechanism Verified placement or handoff Evidence
Delegate callbacks ARSessionDelegate, ARSCNViewDelegate Session callbacks update labels and the Save button; the renderer callback attaches the node. The source does not set delegateQueue, so it does not itself establish the callback queue. ARPersistence/ViewController.swift:55, ARPersistence/ViewController.swift:75, ARPersistence/ViewController.swift:92
Completion handler getCurrentWorldMap { worldMap, error in } Captures the snapshot, archives, and writes inside the handler; only the Load button update is submitted to the main queue. ARPersistence/ViewController.swift:166, ARPersistence/ViewController.swift:178
Main-queue scheduling DispatchQueue.main.async Alert presentation in showAlert and in the session-failure handler. ARPersistence/Utilities.swift:94, ARPersistence/ViewController.swift:135
Transfer contract SnapshotAnchor: ARAnchor, @unchecked Sendable The compiler’s sendability check is waived; the class has a single immutable stored property (imageData). No synchronization primitive is involved. ARPersistence/SnapshotAnchor.swift:10, ARPersistence/SnapshotAnchor.swift:12
Shared-state safety None explicit virtualObjectAnchor and isRelocalizingMap are read and written from delegate callbacks and IB actions with no lock, queue, or actor. ARPersistence/ViewController.swift:80, ARPersistence/ViewController.swift:280

No Swift concurrency, task, or Combine appears. The project sets no default actor isolation.

Reference code

ARPersistence/ViewController.swift:75 — relocalization restores the anchor reference and re-attaches content

        func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard anchor.name == virtualObjectAnchorName
            else { return }
        
        // save the reference to the virtual object anchor when the anchor is added from relocalizing
        if virtualObjectAnchor == nil {
            virtualObjectAnchor = anchor
        }
        node.addChildNode(virtualObject)
    }

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
Event delivery ARSessionDelegate / ARSessionObserver methods Tracking changes, per-frame mapping status, interruption, failure, relocalization permission ARPersistence/ViewController.swift:88, ARPersistence/ViewController.swift:111, ARPersistence/ViewController.swift:147
Event delivery ARSCNViewDelegate Node creation for added anchors ARPersistence/ViewController.swift:75
Event delivery Target-action Save, Load, Reset buttons and the scene tap ARPersistence/Base.lproj/Main.storyboard:43, ARPersistence/Base.lproj/Main.storyboard:165
State propagation Per-frame UI derivation session(_:didUpdate:) enables Save only when mapping is .extending/.mapped and the object anchor is in the frame ARPersistence/ViewController.swift:94
Persistence NSKeyedArchiver/NSKeyedUnarchiver with secure coding Whole ARWorldMap, including custom anchors, written to map.arexperience ARPersistence/ViewController.swift:176, ARPersistence/ViewController.swift:199, ARPersistence/SnapshotAnchor.swift:40
Swift module import UIKit, SceneKit, ARKit Controller dependencies ARPersistence/ViewController.swift:8, ARPersistence/ViewController.swift:9, ARPersistence/ViewController.swift:10
Swift module import simd, ARKit Utility extensions ARPersistence/Utilities.swift:8, ARPersistence/Utilities.swift:9
Privacy declaration NSCameraUsageDescription Camera access string ARPersistence/Info.plist:25

Class and protocol design

Reference code

ARPersistence/SnapshotAnchor.swift:40 — the custom anchor participates in secure coding so it survives the archive

    override class var supportsSecureCoding: Bool {
        return true
    }
    
    required init?(coder aDecoder: NSCoder) {
        if let snapshot = aDecoder.decodeObject(of: NSData.self, forKey: "snapshot") as? Data {
            self.imageData = snapshot
        } else {
            return nil
        }
        
        super.init(coder: aDecoder)
    }
    
    override func encode(with aCoder: NSCoder) {
        super.encode(with: aCoder)
        aCoder.encode(imageData, forKey: "snapshot")
    }
Type Responsibility Depends on
AppDelegate @UIApplicationMain entry; returns the default scene configuration UIKit
SceneDelegate Holds the window; scene callbacks are empty apart from a type check UIKit
ViewController Session setup, delegate callbacks, placement, save/load/reset, feedback UI ARSCNView, ARSession, SnapshotAnchor
SnapshotAnchor Camera JPEG plus capture transform, NSSecureCoding, anchor copying (init(anchor:)) ARAnchor, Core Image
Utilities.swift extensions Status descriptions, feedback strings, ARWorldMap.snapshotAnchor, UIViewController.showAlert, orientation mapping ARKit, UIKit
RoundedButton Styling; gray background when disabled UIButton

The sample declares no local protocol. Behavior is added to framework types with extensions, including two @retroactive CustomStringConvertible conformances on ARKit enums (ARPersistence/Utilities.swift:11, ARPersistence/Utilities.swift:28).

Access control

Symbol Access Verified effect Likely rationale
updateSessionInfoLabel(for:trackingState:) private Only ViewController can call it (ARPersistence/ViewController.swift:243). Inference: one internal place maps tracking and mapping state to user guidance.
IB outlets implicitly internal, weak Interface Builder connects them; the view hierarchy keeps the views alive (ARPersistence/ViewController.swift:15). Inference: the storyboard sets propertyAccessControl="none", so outlets follow the default level.
virtualObjectAnchor, isRelocalizingMap, mapSaveURL, defaultConfiguration implicitly internal Reachable from other module code, although only ViewController uses them (ARPersistence/ViewController.swift:297, ARPersistence/ViewController.swift:228). —
WorldMappingStatus.description, TrackingState.description public Required by the retroactive CustomStringConvertible conformance on public framework types (ARPersistence/Utilities.swift:12, ARPersistence/Utilities.swift:29). Inference: protocol requirements on a public type’s conformance must be at least as visible as the conformance.
SnapshotAnchor.imageData implicitly internal let Readable in the module, immutable after initialization (ARPersistence/SnapshotAnchor.swift:12). —

Reference code

ARPersistence/Utilities.swift:11 — a public requirement inside a retroactive conformance

extension ARFrame.WorldMappingStatus: @retroactive CustomStringConvertible {
    public var description: String {
        switch self {
        case .notAvailable:
            return "Not Available"
        case .limited:
            return "Limited"
        case .extending:
            return "Extending"
        case .mapped:
            return "Mapped"
        @unknown default:
            return "Unknown"
        }
    }
}

Logic ownership and placement

Logic Owning type or file Placement rationale
World tracking settings ViewController.defaultConfiguration Observed: horizontal planes and automatic environment texturing, shared by start, load, and reset (ARPersistence/ViewController.swift:232).
Save gating session(_:didUpdate:) Observed: Save is enabled only for a sufficiently mapped world that contains the placed anchor (ARPersistence/ViewController.swift:96).
Snapshot capture and encoding SnapshotAnchor.init?(capturing:) Observed: JPEG from the current frame’s captured image, oriented for the device (ARPersistence/SnapshotAnchor.swift:14).
Relocalization guidance updateSessionInfoLabel(for:trackingState:) Observed: shows the snapshot while .limited(.relocalizing) and isRelocalizingMap (ARPersistence/ViewController.swift:264).
Placement handleSceneTap(_:) Observed: blocked while relocalizing without an anchor; replaces any existing anchor (ARPersistence/ViewController.swift:280, ARPersistence/ViewController.swift:290).
User-facing strings for ARKit states Utilities.swift Observed: extensions keep presentation text out of the controller.

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks ARPersistence/ViewController.swift:12 (ARSCNViewDelegate, ARSessionDelegate), ARPersistence/ViewController.swift:55 (sceneView.session.delegate = self), ARPersistence/Base.lproj/Main.storyboard:21 ARKit pushes tracking, mapping, anchor, and failure events to one owner, which keeps all AR state transitions in one class. Tradeoff: the controller combines UI, session, and persistence responsibilities.

The single controller owns the whole feature; no further architecture label is claimed from the ViewController name.

Naming conventions

  • Types: UIKit role names (AppDelegate, SceneDelegate, ViewController), …Anchor for the ARAnchor subclass, Rounded… for styled controls.
  • IB actions read as commands (saveExperience(_:), loadExperience(_:), resetTracking(_:), handleSceneTap(_:)); outlets name the view (sceneView, statusLabel, snapshotThumbnail).
  • “Experience” is the user-facing term for a saved world map, used in the action names and the file extension .arexperience (ARPersistence/ViewController.swift:159).
  • State flags read as questions (isRelocalizingMap); derived values are nouns (mapDataFromFile, defaultConfiguration, snapshotAnchor).
  • Anchor identity uses a string constant, virtualObjectAnchorName, rather than a literal at each comparison.

Architecture takeaways

  • Persist spatial content as anchors inside the world map. Restore content when ARKit re-adds those anchors, instead of saving scene geometry.
  • Extend the map with your own data by subclassing ARAnchor and implementing secure coding, as SnapshotAnchor does for the relocalization image.
  • Derive save readiness from worldMappingStatus on every frame and expose it as button state.
  • Use one computed configuration for start, reset, and load so every path runs the same settings, then add initialWorldMap only for load.
  • One delegate-owning controller is simple for a single-screen sample; separating persistence and session state would be the first split if the feature grew.

Source map

Source file Relevant symbols
ARPersistence/AppDelegate.swift AppDelegate, application(_:configurationForConnecting:options:)
ARPersistence/SceneDelegate.swift SceneDelegate
ARPersistence/ViewController.swift ViewController, delegate methods, saveExperience(_:), loadExperience(_:), resetTracking(_:), handleSceneTap(_:), defaultConfiguration
ARPersistence/SnapshotAnchor.swift SnapshotAnchor, init?(capturing:), secure coding
ARPersistence/Utilities.swift WorldMappingStatus.description, TrackingState.localizedFeedback, ARWorldMap.snapshotAnchor, showAlert
ARPersistence/Base.lproj/Main.storyboard ARSCNView delegate outlet, action connections
ARPersistence/Info.plist Scene manifest, NSCameraUsageDescription
ARPersistence.xcodeproj/project.pbxproj Target, deployment target, device family