Recognizing and Labeling Arbitrary Objects
At a glance
| Item | Summary |
|---|---|
| Purpose | Classify ARKit camera frames with a Core ML model through Vision, and let the person tap to place an ARAnchor labeled with the current classification. |
| App architecture | A UIKit storyboard app. AppDelegate checks ARKit support and supplies the scene configuration; an empty SceneDelegate lets the scene manifest load Main.storyboard. The main ViewController owns the ARSKView, the Vision request, and the label map. A child StatusViewController, embedded by a storyboard container segue, shows messages and reports restart taps through a closure. |
| Main patterns | View-controller organization (a parent controller plus an embedded status child) and delegate callbacks from ARSKView and ARSession. |
| Project style | Six Swift files: ViewController.swift and TemplateLabelNode.swift at the top level; app delegate, scene delegate, status controller, and utilities under Support/. The model ships as Resources/Inceptionv3.mlmodel, compiled into a generated Inceptionv3 class. |
| Execution model | No Swift concurrency. Vision work runs on a private serial DispatchQueue; results return with DispatchQueue.main.async. A single retained pixel buffer gates how many frames are in flight. Status messages use main-run-loop Timers. |
| State/event model | Direct property mutation, delegate callbacks, a restartExperienceHandler closure from child to parent, and a [UUID: String] map that links anchors to label text. |
| Key frameworks/packages | ARKit, Vision, SpriteKit, UIKit, and the Core ML model’s generated class. The project declares no Swift package. |
Project structure
ARKitVision.xcodeproj/ one app target, Swift 5, iOS 15.0 deployment target
ARKitVision/
├── ViewController.swift session, Vision request, tap-to-label, AR delegates
├── TemplateLabelNode.swift SKReferenceNode loaded from LabelScene.sks
├── Support/
│ ├── AppDelegate.swift @UIApplicationMain; ARKit check; scene configuration
│ ├── SceneDelegate.swift UIWindowSceneDelegate with empty lifecycle methods
│ ├── StatusViewController.swift message panel, timers, restart button
│ └── Utilities.swift CGImagePropertyOrientation(UIDeviceOrientation)
└── Resources/
├── Main.storyboard ViewController + embedded StatusViewController
├── Inceptionv3.mlmodel compiled in the Sources phase
├── LabelScene.sks label template
└── Info.plist UIApplicationSceneManifest, arkit capability
Structure observations
Support/holds code that is reusable AR scaffolding (status messaging, orientation conversion, lifecycle delegates); the recognition feature itself is the two top-level files.- The
.mlmodelis listed in the target’s Sources build phase (ARKitVision.xcodeproj/project.pbxproj:200), which is whyViewControllercan refer to a generatedInceptionv3type without any Swift file declaring it. - The scene manifest names
$(PRODUCT_MODULE_NAME).SceneDelegate(ARKitVision/Resources/Info.plist:59).SceneDelegateonly checks the scene type (ARKitVision/Support/SceneDelegate.swift:15); the storyboard creates both controllers.
Overall architecture
flowchart LR
App["AppDelegate"] -->|"UISceneConfiguration"| Scene["SceneDelegate + Main.storyboard"]
Scene --> VC["ViewController"]
Scene -->|"embed segue"| Status["StatusViewController (child)"]
VC -->|"IBOutlet"| View["ARSKView + ARSession"]
View -. "didUpdate frame" .-> VC
VC -->|"visionQueue.async"| Vision["VNImageRequestHandler + VNCoreMLRequest (Inceptionv3)"]
Vision -. "completionHandler" .-> VC
VC -->|"showMessage"| Status
Status -. "restartExperienceHandler" .-> VC
VC -->|"ARAnchor + TemplateLabelNode"| View
Reference code
ARKitVision/ViewController.swift:35 — child lookup and restart callback wiring
class ViewController: UIViewController, UIGestureRecognizerDelegate, ARSKViewDelegate, ARSessionDelegate {
// ...
private lazy var statusViewController: StatusViewController = {
return children.lazy.compactMap({ $0 as? StatusViewController }).first!
}()
// MARK: - View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Configure and present the SpriteKit scene that draws overlay content.
let overlayScene = SKScene()
overlayScene.scaleMode = .aspectFill
sceneView.delegate = self
sceneView.presentScene(overlayScene)
sceneView.session.delegate = self
// Hook up status view controller callback.
statusViewController.restartExperienceHandler = { [unowned self] in
self.restartSession()
}
}
// ...
}Interpretation
Observed: the two controllers communicate in one direction each. The parent finds the child among children and calls its message API; the child knows nothing about the parent and reports the restart button through a stored closure (ARKitVision/Support/StatusViewController.swift:44). The storyboard, not code, creates the parent-child relationship (an embed segue).
Inference: keeping status UI in a child controller lets the same StatusViewController file be reused across AR samples without depending on any feature controller.
Ownership and state
classDiagram
ViewController o-- ARSKView : weak @IBOutlet sceneView
ViewController o-- StatusViewController : lazy lookup in children
ViewController *-- Inceptionv3 : _inceptionv3Model (created on first access)
ViewController *-- VNCoreMLRequest : lazy classificationRequest
ViewController *-- DispatchQueue : visionQueue
ViewController *-- CVPixelBuffer : currentBuffer (in-flight frame)
ViewController *-- AnchorLabels : anchorLabels [UUID: String]
StatusViewController *-- Timer : messageHideTimer, timers
StatusViewController o-- RestartHandler : restartExperienceHandler
Ownership evidence
ARKitVision/ViewController.swift:113 — the in-flight buffer and the serial queue
class ViewController: UIViewController, UIGestureRecognizerDelegate, ARSKViewDelegate, ARSessionDelegate {
// ...
// The pixel buffer being held for analysis; used to serialize Vision requests.
private var currentBuffer: CVPixelBuffer?
// Queue for dispatching vision classification requests
private let visionQueue = DispatchQueue(label: "com.example.apple-samplecode.ARKitVision.serialVisionQueue")
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
| Storyboard | ARSKView, both controllers |
Creates them; ViewController.sceneView is a weak outlet (ARKitVision/ViewController.swift:15) |
Storyboard |
ViewController |
Inceptionv3 model |
private var _inceptionv3Model, created by the inceptionv3Model getter on first access (ARKitVision/ViewController.swift:18, ARKitVision/ViewController.swift:21) |
ViewController |
ViewController |
VNCoreMLRequest |
private lazy var classificationRequest; the completion handler captures self weakly (ARKitVision/ViewController.swift:92, ARKitVision/ViewController.swift:96) |
Created once |
ViewController |
currentBuffer |
Set in the frame callback, cleared by defer inside the Vision work item (ARKitVision/ViewController.swift:85, ARKitVision/ViewController.swift:127) |
ViewController, from two queues |
ViewController |
identifierString, confidence |
Latest classification, written in processClassifications (ARKitVision/ViewController.swift:136) |
ViewController |
ViewController |
anchorLabels |
Label text keyed by anchor identifier; filled on tap, read when ARKit asks for a node, cleared on restart (ARKitVision/ViewController.swift:175, ARKitVision/ViewController.swift:263) |
ViewController |
StatusViewController |
messageHideTimer, timers |
private timers invalidated before replacement (ARKitVision/Support/StatusViewController.swift:50, ARKitVision/Support/StatusViewController.swift:52) |
StatusViewController |
StatusViewController |
restartExperienceHandler |
Implicitly internal closure property, assigned by the parent |
Parent controller |
Observed: anchors and labels are linked by identifier rather than by subclassing ARAnchor. placeLabelAtLocation adds a plain ARAnchor and records anchorLabels[anchor.identifier]; view(_:didAdd:for:) looks the text up and attaches a TemplateLabelNode (ARKitVision/ViewController.swift:188, ARKitVision/ViewController.swift:194).
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 worker queue | DispatchQueue(label: "...serialVisionQueue") (serial by default) |
requestHandler.perform([classificationRequest]) runs in work items on this queue, one at a time |
ARKitVision/ViewController.swift:116, ARKitVision/ViewController.swift:124 |
| Backpressure | guard currentBuffer == nil before retaining frame.capturedImage |
At most one camera buffer is held for Vision; frames that arrive while it is set are dropped. The comment states the reason: holding too many buffers would starve the camera | ARKitVision/ViewController.swift:80, ARKitVision/ViewController.swift:79 |
| Release point | defer { self.currentBuffer = nil } inside the queue work item |
The gate reopens after perform returns |
ARKitVision/ViewController.swift:127 |
| Main-queue UI | DispatchQueue.main.async { [weak self] in self?.displayClassifierResults() } |
Status text is shown from the main queue after each classification | ARKitVision/ViewController.swift:158 |
| Main-queue alert | DispatchQueue.main.async { self.displayErrorMessage(...) } |
Session-failure alert | ARKitVision/ViewController.swift:228 |
| Run-loop timers | Timer.scheduledTimer(...) in the status controller |
Auto-hide, scheduled, and escalation messages; each is invalidated before replacement | ARKitVision/Support/StatusViewController.swift:66, ARKitVision/Support/StatusViewController.swift:103 |
| Shared-state safety | None | currentBuffer, identifierString, and confidence are written on visionQueue and read from the frame callback, the main queue, and the tap action, with no lock |
ARKitVision/ViewController.swift:136, ARKitVision/ViewController.swift:188 |
| Resource choice | request.usesCPUOnly = true |
The comment says CPU-only Vision leaves GPU resources for rendering | ARKitVision/ViewController.swift:104 |
Reference code
ARKitVision/ViewController.swift:124 — one frame at a time through the serial queue
class ViewController: UIViewController, UIGestureRecognizerDelegate, ARSKViewDelegate, ARSessionDelegate {
// ...
func session(_ session: ARSession, didUpdate frame: ARFrame) {
// Do not enqueue other buffers for processing while another Vision task is still running.
// The camera stream has only a finite amount of buffers available; holding too many buffers for analysis would starve the camera.
guard currentBuffer == nil, case .normal = frame.camera.trackingState else {
return
}
// Retain the image buffer for Vision processing.
self.currentBuffer = frame.capturedImage
classifyCurrentImage()
}
// ...
private func classifyCurrentImage() {
// Most computer vision tasks are not rotation agnostic so it is important to pass in the orientation of the image with respect to device.
let orientation = CGImagePropertyOrientation(UIDevice.current.orientation)
let requestHandler = VNImageRequestHandler(cvPixelBuffer: currentBuffer!, orientation: orientation)
visionQueue.async {
do {
// Release the pixel buffer when done, allowing the next buffer to be processed.
defer { self.currentBuffer = nil }
try requestHandler.perform([self.classificationRequest])
} catch {
print("Error: Vision request failed with error \"\(error)\"")
}
}
}
// ...
}Interpretation: currentBuffer is a backpressure flag, not protected shared state; it limits work to one frame, but it is read and written from different queues without synchronization. Not established by source: which queue delivers ARSessionDelegate callbacks (no delegateQueue is set) or on which queue Vision calls the request’s completion handler.
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 |
|---|---|---|---|
| Classification to UI | processClassifications stores the top result above 0.5 confidence, then the main queue formats it into a status message |
Latest result only; no history | ARKitVision/ViewController.swift:149, ARKitVision/ViewController.swift:169 |
| Classification to anchors | anchorLabels[anchor.identifier] = identifierString at tap time |
The label is the classification current at the moment of the tap | ARKitVision/ViewController.swift:188 |
| Child to parent | restartExperienceHandler closure invoked by @IBAction restartExperience |
Restart is the only upward event | ARKitVision/Support/StatusViewController.swift:119 |
| Tracking feedback | cameraDidChangeTrackingState calls showTrackingQualityInfo and escalateFeedback |
Limited tracking escalates to a persistent message after 3 seconds | ARKitVision/ViewController.swift:203, ARKitVision/ViewController.swift:208 |
| Framework import | Vision, ARKit, SpriteKit, UIKit |
Main controller compilation dependencies | ARKitVision/ViewController.swift:11, ARKitVision/ViewController.swift:10, ARKitVision/ViewController.swift:9, ARKitVision/ViewController.swift:8 |
| Framework import | SpriteKit |
Label template node | ARKitVision/TemplateLabelNode.swift:8 |
| Model dependency | Inceptionv3.mlmodel in Sources |
Generated model class used by VNCoreMLModel(for:) |
ARKitVision.xcodeproj/project.pbxproj:200, ARKitVision/ViewController.swift:95 |
The source uses no Combine, notifications, or observation framework, and the project declares no Swift package.
Class and protocol design
classDiagram
class ARSKViewDelegate {
<<protocol>>
}
class ARSessionDelegate {
<<protocol>>
}
ViewController ..|> ARSKViewDelegate
ViewController ..|> ARSessionDelegate
ViewController --> StatusViewController : showMessage, escalateFeedback
ViewController --> TemplateLabelNode : creates per anchor
TemplateLabelNode --|> SKReferenceNode
SceneDelegate ..|> UIWindowSceneDelegate
Reference code
ARKitVision/TemplateLabelNode.swift:14 — label node loaded from a SpriteKit template
class TemplateLabelNode: SKReferenceNode {
private let text: String
init(text: String) {
self.text = text
// Force call to designated init(fileNamed: String?), not convenience init(fileNamed: String)
super.init(fileNamed: Optional.some("LabelScene"))
setScale(0.2)
}
// ...
override func didLoad(_ node: SKNode?) {
// Apply text to both labels loaded from the template.
guard let parent = node?.childNode(withName: "LabelNode") else {
fatalError("misconfigured SpriteKit template file")
}
for case let label as SKLabelNode in parent.children {
label.name = text
label.text = text
}
}
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
ViewController |
Session lifecycle, frame gating, Vision request, tap-to-anchor, AR error handling | UIViewController, ARSKViewDelegate, ARSessionDelegate, UIGestureRecognizerDelegate |
StatusViewController |
Message panel, scheduled and escalated messages, restart button | UIViewController, ARCamera.TrackingState extension |
StatusViewController.MessageType |
Keys for scheduled-message timers | static var all for bulk cancellation |
TemplateLabelNode |
Applies label text to a node loaded from LabelScene.sks |
SKReferenceNode |
CGImagePropertyOrientation.init(_:) |
Maps device orientation to Vision image orientation | Utilities.swift |
Observed: the sample declares no local protocol. The parent-child contract is a concrete class plus a closure property.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
_inceptionv3Model, inceptionv3Model, statusViewController, classificationRequest, currentBuffer, visionQueue (ARKitVision/ViewController.swift:18, ARKitVision/ViewController.swift:116) |
private |
Model, request, and queue are reachable only inside ViewController |
Inference: recognition internals are not part of any other type’s API. |
identifierString, confidence, anchorLabels (ARKitVision/ViewController.swift:136, ARKitVision/ViewController.swift:175) |
private |
Classification and label state stay in the controller | Same as above. |
processClassifications(for:error:) (ARKitVision/ViewController.swift:140) |
implicit internal |
Callable from the module; only the request’s completion handler calls it | No explicit restriction. |
StatusViewController outlets (ARKitVision/Support/StatusViewController.swift:35) |
weak private @IBOutlet |
The parent cannot touch the panel’s views directly | Inference: forces callers through showMessage and friends. |
displayDuration, messageHideTimer, timers (ARKitVision/Support/StatusViewController.swift:47) |
private |
Timer bookkeeping is internal to the status controller | Inference: callers schedule by MessageType, not by timer. |
restartExperience(_:) (ARKitVision/Support/StatusViewController.swift:119) |
@IBAction private |
Only the storyboard connection triggers it | Inference: the closure is the public hook. |
TemplateLabelNode.text (ARKitVision/TemplateLabelNode.swift:12) |
private let |
Text is fixed at initialization | Immutable label content. |
Reference code
ARKitVision/Support/StatusViewController.swift:35 — private outlets behind a message API
class StatusViewController: UIViewController {
// ...
@IBOutlet weak private var messagePanel: UIVisualEffectView!
@IBOutlet weak private var messageLabel: UILabel!
@IBOutlet weak private var restartExperienceButton: UIButton!
// MARK: - Properties
/// Trigerred when the "Restart Experience" button is tapped.
var restartExperienceHandler: () -> Void = {}
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Frame gating and Vision dispatch | ViewController.session(_:didUpdate:), classifyCurrentImage() |
Only frames with .normal tracking are classified (ARKitVision/ViewController.swift:80). |
| Image orientation | CGImagePropertyOrientation(UIDeviceOrientation) |
Converts UIDevice.current.orientation for Vision (ARKitVision/Support/Utilities.swift:13, ARKitVision/ViewController.swift:121). |
| Model input shaping | classificationRequest |
.centerCrop matches how the model was trained, per the comment (ARKitVision/ViewController.swift:101). |
| Result selection | processClassifications(for:error:) |
First result above 0.5 confidence; keeps the text before the first comma (ARKitVision/ViewController.swift:149). |
| Anchor placement | placeLabelAtLocation(sender:) |
Hit-tests feature points and estimated horizontal planes (ARKitVision/ViewController.swift:180). |
| Interruption handling | sessionWasInterrupted, sessionShouldAttemptRelocalization, setOverlaysHidden(_:) |
Hide overlays on interruption, fade them back after relocalization (ARKitVision/ViewController.swift:233, ARKitVision/ViewController.swift:247). |
| Message escalation | StatusViewController.escalateFeedback(for:inSeconds:) |
Adds the tracking-state recommendation and disables auto-hide (ARKitVision/Support/StatusViewController.swift:100). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | ViewController runs and pauses the session in viewWillAppear/viewWillDisappear and finds an embedded StatusViewController child (ARKitVision/ViewController.swift:57, ARKitVision/ViewController.swift:36) |
Status UI is isolated in a child controller; recognition, placement, and session handling stay in one parent controller. |
| Delegate or data-source callbacks | sceneView.delegate = self, sceneView.session.delegate = self; view(_:didAdd:for:) supplies label nodes (ARKitVision/ViewController.swift:47, ARKitVision/ViewController.swift:49, ARKitVision/ViewController.swift:193) |
Frames, tracking changes, and node creation all arrive as callbacks on the parent controller. |
Naming conventions
- Types: framework-role names (
ViewController,StatusViewController,AppDelegate,SceneDelegate) plusTemplateLabelNode, named for how it is built (from a template scene). - Methods: actions say what they do (
classifyCurrentImage,processClassifications(for:error:),displayClassifierResults,placeLabelAtLocation(sender:),restartSession); the status API usesshow…,schedule…,cancel…,escalate…. - Properties:
restartExperienceHandlerfor the closure hook; a leading underscore marks the backing store of the computedinceptionv3Model. - Files: one primary type per file; reusable scaffolding sits in
Support/.
Architecture takeaways
- A single retained pixel buffer is a simple backpressure gate that keeps a slow model from starving ARKit’s camera buffer pool.
- A serial queue serializes Vision requests; UI updates hop back to the main queue explicitly.
- Associating labels with anchors through a
[UUID: String]map avoids anARAnchorsubclass. - An embedded child controller with a closure callback keeps status UI reusable and ignorant of the feature controller.
- Controller state crosses the Vision queue and the main queue without a lock; the gate limits concurrency but does not make the state thread-safe.
Source map
| Source file | Relevant symbols |
|---|---|
ARKitVision/ViewController.swift |
ViewController, inceptionv3Model, statusViewController, classificationRequest, currentBuffer, visionQueue, classifyCurrentImage(), processClassifications(for:error:), placeLabelAtLocation(sender:), anchorLabels, restartSession() |
ARKitVision/Support/StatusViewController.swift |
StatusViewController, MessageType, showMessage(_:autoHide:), escalateFeedback(for:inSeconds:), restartExperienceHandler |
ARKitVision/TemplateLabelNode.swift |
TemplateLabelNode |
ARKitVision/Support/Utilities.swift |
CGImagePropertyOrientation.init(_:) |
ARKitVision/Support/AppDelegate.swift |
AppDelegate |
ARKitVision/Support/SceneDelegate.swift |
SceneDelegate |
ARKitVision/Resources/Info.plist |
UIApplicationSceneManifest, UIRequiredDeviceCapabilities |
ARKitVision.xcodeproj/project.pbxproj |
Inceptionv3.mlmodel in Sources, SWIFT_VERSION, deployment target |