Detecting Images in an AR Experience
At a glance
| Item | Summary |
|---|---|
| Purpose | React to known 2D images in the user’s environment, and use their positions to place AR content. |
| App architecture | A storyboard UIKit app with scene-based lifecycle. One ViewController owns the ARSCNView session setup and receives SceneKit-renderer and AR-session callbacks. It embeds a child StatusViewController that shows timed messages and a restart button. |
| Main patterns | View-controller organization (parent and embedded child controller with a closure callback), Delegate or data-source callbacks (ARSCNViewDelegate, ARSessionDelegate) |
| Project style | One iOS target. ViewController is split into a primary file (session setup and image results) and a +ARSessionDelegate extension (tracking state, errors, interruptions, restart). The status UI is in Additional View Controllers/. |
| Execution model | Renderer callbacks put SceneKit node changes on a private serial updateQueue and status-UI updates on DispatchQueue.main. Message timing uses run-loop Timers and a DispatchQueue.main.asyncAfter restart debounce. No Swift concurrency. |
| State/event model | Delegate callbacks from ARKit and SceneKit, a closure (restartExperienceHandler) from the child to the parent, and direct method calls from the parent to the child. |
| Key frameworks/packages | ARKit, SceneKit, UIKit. No package dependencies. |
Project structure
Source bundle/
├── ARKitImageDetection/
│ ├── AppDelegate.swift ARKit support check, scene configuration
│ ├── SceneDelegate.swift window holder; storyboard comes from Info.plist
│ ├── ViewController.swift session setup, image-anchor visualization
│ ├── ViewController+ARSessionDelegate.swift tracking state, errors, interruption, restart
│ ├── Additional View Controllers/
│ │ └── StatusViewController.swift message panel, timers, restart button
│ ├── Base.lproj/Main.storyboard ARSCNView plus embedded status controller
│ └── Resources/ (Assets.xcassets "AR Resources", Info.plist)
└── ARKitImageDetection.xcodeproj/
Structure observations
- The window and root controller come from configuration, not code. The Info.plist scene manifest names
SceneDelegateand theMainstoryboard (ARKitImageDetection/Resources/Info.plist:68), andSceneDelegateonly checks for aUIWindowScene(ARKitImageDetection/SceneDelegate.swift:15). - The storyboard embeds
StatusViewControllerin a container view insideViewController’s scene (ARKitImageDetection/Base.lproj/Main.storyboard:130). - Reference images are an asset-catalog group named “AR Resources”, loaded at session start (
ARKitImageDetection/ViewController.swift:71).
Overall architecture
flowchart LR
Plist["Info.plist scene manifest"] --> Scene["SceneDelegate"]
Scene --> Storyboard["Main.storyboard"]
Storyboard --> VC["ViewController"]
VC --> Status["StatusViewController (child)"]
VC --> Session["ARSCNView / ARSession"]
Session -->|ARSCNViewDelegate, ARSessionDelegate| VC
Status -->|restartExperienceHandler| VC
Reference code
ARKitImageDetection/ViewController.swift:41 — the parent finds the embedded child, registers as delegate, and wires the restart closure
class ViewController: UIViewController, ARSCNViewDelegate {
// ...
lazy var statusViewController: StatusViewController = {
return children.lazy.compactMap({ $0 as? StatusViewController }).first!
}()
// ...
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.session.delegate = self
// Hook up status view controller callback(s).
statusViewController.restartExperienceHandler = { [unowned self] in
self.restartExperience()
}
}
// ...
}Interpretation
Dependencies point one way. ViewController knows StatusViewController and calls its message API. The child exposes only a () -> Void closure and never references its parent’s type. Both AR callbacks arrive at ViewController itself, which is the delegate for the view and for the session. AppDelegate checks that ARWorldTrackingConfiguration is supported at launch and returns the scene configuration name. It does not build any UI.
Ownership and state
classDiagram
ViewController o-- ARSCNView : IBOutlet sceneView
ViewController o-- StatusViewController : lazy lookup in children
ViewController *-- DispatchQueue : let updateQueue
StatusViewController *-- Timer : timers and messageHideTimer
StatusViewController --> ViewController : restartExperienceHandler closure
ARSCNView *-- ARSession : session
Ownership evidence
ARKitImageDetection/ViewController.swift:24 — a serial queue and a computed accessor to the view-owned session
/// A serial queue for thread safety when modifying the SceneKit node graph.
let updateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! +
".serialSceneKitQueue")
/// Convenience accessor for the session owned by ARSCNView.
var session: ARSession {
return sceneView.session
}ARKitImageDetection/Additional View Controllers/StatusViewController.swift:47 — the child keeps its own timers and the restart callback
/// Trigerred when the "Restart Experience" button is tapped.
var restartExperienceHandler: () -> Void = {}
/// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages.
private let displayDuration: TimeInterval = 6
// Timer for hiding messages.
private var messageHideTimer: Timer?
private var timers: [MessageType: Timer] = [:]| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
Storyboard / ARSCNView |
ARSession |
The session belongs to the view; ViewController reaches it through a computed session property |
ViewController runs and pauses it (ARKitImageDetection/ViewController.swift:77) |
| Storyboard (embed segue) | StatusViewController |
Created by the container; ViewController finds it lazily in children |
ViewController calls its API |
ViewController |
updateQueue |
Creates and keeps a private-label serial queue for node-graph edits | ViewController |
ViewController |
isRestartAvailable |
Boolean debounce for restarts (ARKitImageDetection/ViewController.swift:65) |
restartExperience() and its delayed reset |
StatusViewController |
timers, messageHideTimer |
Retains scheduled Timers per message type so that they can be invalidated |
StatusViewController only (private) |
StatusViewController |
restartExperienceHandler |
Stores the parent’s closure, which captures the parent [unowned self] |
Assigned by ViewController |
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 |
|---|---|---|---|
| Serial queue | DispatchQueue(label:), updateQueue.async |
Plane-node creation and node.addChildNode for each detected image run on the serial queue that the source documents as protecting the SceneKit node graph. |
ARKitImageDetection/ViewController.swift:87 |
| Main-queue scheduling | DispatchQueue.main.async |
From the renderer callback, scheduled messages are cancelled and the “Detected image” message is shown on the main queue. | ARKitImageDetection/ViewController.swift:112 |
| Main-queue scheduling | DispatchQueue.main.async |
Session failure presents the error alert on the main queue. | ARKitImageDetection/ViewController+ARSessionDelegate.swift:38 |
| Delayed scheduling | DispatchQueue.main.asyncAfter |
isRestartAvailable becomes true again 5 seconds after a restart. |
ARKitImageDetection/ViewController+ARSessionDelegate.swift:90 |
| Run-loop timers | Timer.scheduledTimer |
Message auto-hide, scheduled hints, and tracking-state escalation. Each timer is stored and invalidated on cancel. | ARKitImageDetection/Additional View Controllers/StatusViewController.swift:98 |
| Delegate queue | No delegateQueue assignment |
Tracking-state and interruption callbacks update StatusViewController and blurView directly. The source never sets the session’s delegate queue. Inference: these callbacks rely on ARKit’s default main-queue delivery. |
ARKitImageDetection/ViewController+ARSessionDelegate.swift:14 |
Shared-state safety is limited to what the source names. Node-graph edits go through updateQueue, and UI updates from the renderer go to the main queue. isRestartAvailable and the timer dictionary have no lock. They are touched only from callbacks and main-queue work.
Reference code
ARKitImageDetection/ViewController.swift:84 — one callback splits work between the serial SceneKit queue and the main queue
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let imageAnchor = anchor as? ARImageAnchor else { return }
let referenceImage = imageAnchor.referenceImage
updateQueue.async {
// Create a plane to visualize the initial position of the detected image.
let plane = SCNPlane(width: referenceImage.physicalSize.width,
height: referenceImage.physicalSize.height)
let planeNode = SCNNode(geometry: plane)
planeNode.opacity = 0.25
// ...
planeNode.runAction(self.imageHighlightAction)
// Add the plane visualization to the scene.
node.addChildNode(planeNode)
}
DispatchQueue.main.async {
let imageName = referenceImage.name ?? ""
self.statusViewController.cancelAllScheduledMessages()
self.statusViewController.showMessage("Detected image “\(imageName)”")
}
}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 | ARSCNViewDelegate |
renderer(_:didAdd:for:) delivers each ARImageAnchor node. |
ARKitImageDetection/ViewController.swift:84 |
| State propagation | ARSessionDelegate |
Tracking-state changes, failures, and interruption begin and end. | ARKitImageDetection/ViewController+ARSessionDelegate.swift:10 |
| State propagation | Closure callback | The child’s restart button calls restartExperienceHandler. |
ARKitImageDetection/Additional View Controllers/StatusViewController.swift:115 |
| Framework import | ARKit |
Session, ARWorldTrackingConfiguration.detectionImages, ARReferenceImage, ARImageAnchor. |
ARKitImageDetection/ViewController.swift:8 |
| Framework import | SceneKit |
SCNPlane, SCNNode, and SCNAction for the highlight overlay. |
ARKitImageDetection/ViewController.swift:9 |
| Framework import | UIKit |
App, scene, and view-controller types. | ARKitImageDetection/SceneDelegate.swift:8 |
Class and protocol design
Reference code
ARKitImageDetection/ViewController+ARSessionDelegate.swift:10 — the session conformance lives in its own extension file
extension ViewController: ARSessionDelegate {
// MARK: - ARSessionDelegate
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
statusViewController.showTrackingQualityInfo(for: camera.trackingState, autoHide: true)
switch camera.trackingState {
case .notAvailable, .limited:
statusViewController.escalateFeedback(for: camera.trackingState, inSeconds: 3.0)
case .normal:
statusViewController.cancelScheduledMessage(for: .trackingStateEscalation)
}
}
// ...
}| Type | Responsibility | Depends on |
|---|---|---|
AppDelegate |
ARKit support check; returns the “Default Configuration” scene configuration | UIApplicationDelegate |
SceneDelegate |
Holds the scene’s window; no other setup |
UIWindowSceneDelegate |
ViewController |
Session configuration and restart, image-anchor visualization, error alert | ARSCNView, StatusViewController |
StatusViewController |
Message panel, scheduled and escalating messages, restart button | Timer, ARCamera.TrackingState |
StatusViewController.MessageType |
Keys for cancellable scheduled messages | — |
ARCamera.TrackingState extension |
presentationString and recommendation text |
ARKit |
No local protocol is declared. The child-to-parent link is a closure property, not a delegate protocol.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
messagePanel, messageLabel, restartExperienceButton (ARKitImageDetection/Additional View Controllers/StatusViewController.swift:30) |
weak private outlets |
ViewController cannot reach the child’s views and must use its methods. |
Inference: the child owns its own presentation. |
displayDuration, messageHideTimer, timers (ARKitImageDetection/Additional View Controllers/StatusViewController.swift:42) |
private |
Timer bookkeeping is confined to the child. | Inference: callers schedule and cancel by MessageType, never by timer. |
restartExperience(_:) (ARKitImageDetection/Additional View Controllers/StatusViewController.swift:114) |
@IBAction private |
Only the storyboard button triggers it. It forwards to the handler. | Inference: the action is not part of the child’s API. |
ViewController.updateQueue, isRestartAvailable, statusViewController |
implicit internal |
Visible to the +ARSessionDelegate extension in another file, which needs isRestartAvailable and statusViewController. |
Inference: private would block the cross-file extension. |
Reference code
ARKitImageDetection/Additional View Controllers/StatusViewController.swift:83 — callers cancel by message type; the timers stay private
func cancelScheduledMessage(for messageType: MessageType) {
timers[messageType]?.invalidate()
timers[messageType] = nil
}
func cancelAllScheduledMessages() {
for messageType in MessageType.all {
cancelScheduledMessage(for: messageType)
}
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Reference-image loading and session run | ViewController.resetTracking() |
Rebuilds the configuration and resets tracking and anchors on every restart. |
| Detected-image visualization | ViewController.renderer(_:didAdd:for:) and imageHighlightAction |
Adds a fading plane. The source comments that image anchors are not tracked after initial detection. |
| Tracking feedback and escalation | +ARSessionDelegate → StatusViewController.escalateFeedback |
The parent maps session state to calls; the child decides the text and timing. |
| Interruption and restart | +ARSessionDelegate (ARKitImageDetection/ViewController+ARSessionDelegate.swift:81) |
Interruption end calls restartExperience(), which is debounced by isRestartAvailable. |
| User-facing tracking strings | ARCamera.TrackingState extension (ARKitImageDetection/Additional View Controllers/StatusViewController.swift:135) |
Kept with the only consumer of the strings. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | ARKitImageDetection/ViewController.swift:20 (child lookup), ARKitImageDetection/Base.lproj/Main.storyboard:130 (embed segue) |
A parent controller owns the AR session, and an embedded child owns the status UI. The child talks back only through a closure. |
| Delegate or data-source callbacks | ARKitImageDetection/ViewController.swift:37, ARKitImageDetection/ViewController+ARSessionDelegate.swift:10 |
ARKit and SceneKit push anchor and session events into the controller. |
Naming conventions
- Types: UIKit role suffixes (
ViewController,StatusViewController,SceneDelegate). The nestedMessageTypeenum names the keys for scheduled messages. - Methods: imperative commands (
resetTracking,restartExperience,showMessage,scheduleMessage,cancelScheduledMessage,escalateFeedback). The handler property is suffixed…Handler. - Booleans:
isRestartAvailable. - Files and extensions:
Type+Protocol.swiftfor a conformance extension (ViewController+ARSessionDelegate.swift).
Architecture takeaways
- Splitting a busy AR view controller by protocol conformance into
Type+Protocol.swiftfiles keeps session-state handling apart from content setup without adding new types. - An embedded child controller with private outlets and a closure callback gives the status UI a narrow interface and a one-way dependency on its parent.
- Renderer callbacks route scene-graph edits and UI updates to two explicitly named queues: a private serial queue and the main queue.
- Timers kept in a dictionary keyed by an enum make every scheduled message cancellable by type.
- A Boolean plus a delayed main-queue reset is a minimal debounce for restarting an expensive session.
Source map
| Source file | Relevant symbols |
|---|---|
ARKitImageDetection/AppDelegate.swift |
AppDelegate, scene configuration |
ARKitImageDetection/SceneDelegate.swift |
SceneDelegate |
ARKitImageDetection/ViewController.swift |
ViewController, updateQueue, resetTracking, renderer(_:didAdd:for:) |
ARKitImageDetection/ViewController+ARSessionDelegate.swift |
session(_:cameraDidChangeTrackingState:), displayErrorMessage, restartExperience |
ARKitImageDetection/Additional View Controllers/StatusViewController.swift |
StatusViewController, MessageType, escalateFeedback, ARCamera.TrackingState extension |
ARKitImageDetection/Resources/Info.plist |
Scene manifest |
ARKitImageDetection/Base.lproj/Main.storyboard |
Embedded status controller |