Sample CodeiOS, iPadOS, Mac CatalystReviewed 2026-07-21View on Apple Developer

Controlling a DockKit accessory using your camera app

At a glance

Item Summary
Purpose Follow subjects in real time using an iPhone that you mount on a DockKit accessory.
App architecture A Swift sample with the source-visible chain DockKit_CameraAppContentViewCameraModelCaptureServiceDockKit APIs.
Main patterns View-controller organization, Protocol-oriented abstraction, Delegate or data-source callbacks, Service object, Publisher-backed observable state, Actor isolation
Project style 31 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries.
Execution model Source-visible boundaries: DispatchQueue(label:), async declaration or closure, actor, Task, @MainActor; none alone proves a background thread.
State/event model Source-visible mechanisms: @Published, AnyCancellable, SwiftUI state property wrapper.
Key frameworks/packages SwiftUI, AVFoundation, Combine, Foundation, UIKit; these are source dependencies, not architecture labels.

Project structure

Source bundle/
└── DockKitCamera/
    ├── DockKit_CameraApp.swift
    ├── Model/
    │   ├── DataTypes.swift
    │   ├── CameraModel.swift
    │   ├── DockAccessoryController.swift
    │   └── DockControllerModel.swift
    ├── Preview Content/
    │   ├── PreviewCameraModel.swift
    │   └── PreviewDockAccessoryControllerModel.swift
    ├── Views/
    │   ├── CameraPreview.swift
    │   └── BatteryView.swift
    ├── CaptureService.swift
    ├── ContentView.swift
    └── DockControlService.swift

Structure observations

  • Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
  • Primary languages: Swift.
  • The verified tree contains 4 project/configuration file(s) and 58 source declaration(s).

Overall architecture

Reference code

DockKitCamera/DockKit_CameraApp.swift:11 — architecture anchor

@main
struct DockKitCameraApp: App {

    @State private var camera = CameraModel()

    @State private var dockController = DockControllerModel()

    var body: some Scene {
        WindowGroup {
            ContentView(camera: camera, dockController: dockController)
                .task {
                    await camera.setTrackingServiceDelegate(dockController)
                    await dockController.setCameraCaptureServiceDelegate(camera)
                    // Start the capture pipeline.
                    await camera.start()
                }
        }
    }
}

Interpretation

The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into DockKit.

Ownership and state

Ownership evidence

DockKitCamera/DockKit_CameraApp.swift:14 — stored dependency or nearest verified ownership anchor

@main
struct DockKitCameraApp: App {
    // ...
    @State private var camera = CameraModel()
    // ...
}
Owner Object or state Relationship Mutation authority
DockKitCameraApp CameraModel (camera) owns wrapper-managed state Owning lexical scope
DockKitCameraApp DockControllerModel (dockController) owns wrapper-managed state Owning lexical scope
DockKitCameraApp Logger (logger) creates and retains Initialized by the owner; the binding is immutable
Movie URL (url) owns value state Initialized by the owner; the binding is immutable

Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.

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
Queue scheduling DispatchQueue(label:) The source constructs a dispatch queue; its label alone does not prove a thread. DockKitCamera/Camera/MovieCapture.swift:63
Suspension boundary async declaration or closure The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. DockKitCamera/Camera/MovieCapture.swift:98
Actor isolation actor The cited type is actor-isolated; this does not select a background thread. DockKitCamera/CaptureService.swift:15
Task creation Task The source creates an unstructured task; surrounding context determines inherited actor isolation. DockKitCamera/CaptureService.swift:98
Main isolation @MainActor The cited annotation marks its attached declaration or closure as main-actor isolated. DockKitCamera/CaptureService.swift:262

@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.

Reference code

DockKitCamera/Camera/MovieCapture.swift:63 — representative execution boundary

final class MovieCapture: NSObject, OutputService {
    // ...
        metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue(label: "MetaDataOutputQueue"))
    // ...
}

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 @Published A published property can emit owner-controlled changes. DockKitCamera/Camera/MovieCapture.swift:15
State propagation AnyCancellable A cancellable value records subscription lifetime management. DockKitCamera/Camera/MovieCapture.swift:48
State propagation SwiftUI state property wrapper A SwiftUI property wrapper supplies or observes UI state. DockKitCamera/ContentView.swift:12
Source import SwiftUI The cited file imports this module; runtime use and architectural role are not inferred. DockKitCamera/ContentView.swift:8
Source import AVFoundation The cited file imports this module; runtime use and architectural role are not inferred. DockKitCamera/Camera/DeviceLookup.swift:8
Source import Combine The cited file imports this module; runtime use and architectural role are not inferred. DockKitCamera/Camera/DeviceLookup.swift:9
Source import Foundation The cited file imports this module; runtime use and architectural role are not inferred. DockKitCamera/CaptureService.swift:8
Source import UIKit The cited file imports this module; runtime use and architectural role are not inferred. DockKitCamera/CaptureService.swift:11

receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.

Class and protocol design

DockKitCamera/Model/DataTypes.swift:113 — representative type boundary

protocol OutputService {
    associatedtype Output: AVCaptureOutput
    var output: Output { get }
    var captureActivity: CaptureActivity { get }
    func updateConfiguration(for device: AVCaptureDevice)
    func setVideoRotationAngle(_ angle: CGFloat)
}
Type Responsibility Depends on or conforms to
DockKitCameraApp Application entry and top-level composition App
OutputService Defines a capability or collaboration contract Concrete collaborators/imported frameworks
DockAccessoryTrackingDelegate Defines a capability or collaboration contract AnyObject
CameraCaptureDelegate Defines a capability or collaboration contract AnyObject
DockController Defines a capability or collaboration contract AnyObject
PreviewCameraModel Feature data or observable state Camera
PreviewView User-interface presentation and input forwarding UIView, PreviewTarget
CaptureService Framework-facing operations Concrete collaborators/imported frameworks
ContentView User-interface presentation and input forwarding Concrete collaborators/imported frameworks
DockControlService Framework-facing operations Concrete collaborators/imported frameworks

The source explicitly defines local protocol relationships: MovieCaptureOutputService, CameraModelCamera, DockControllerModelDockController, PreviewCameraModelCamera, PreviewSourceStubPreviewSource, PreviewDockControllerModelDockController.

Access control

Symbol Access Verified effect Likely rationale
frontCameraDiscoverySession (DockKitCamera/Camera/DeviceLookup.swift:15) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
backCameraDiscoverySession (DockKitCamera/Camera/DeviceLookup.swift:16) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
externalCameraDiscoverSession (DockKitCamera/Camera/DeviceLookup.swift:17) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
captureActivity (DockKitCamera/Camera/MovieCapture.swift:15) private(set) Read access follows the declaration; writes remain in the private scope. Inference: allow observation while reserving invariant-changing writes for the owner.

Reference code

DockKitCamera/Camera/DeviceLookup.swift:15 — representative boundary

final class DeviceLookup {
    // ...
    private let frontCameraDiscoverySession: AVCaptureDevice.DiscoverySession
    // ...
}

Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.

Logic ownership and placement

Logic Owning type or file Placement rationale
Application entry and top-level composition DockKitCameraApp The source’s App suffix makes this role explicit.
View lifecycle, callbacks, and feature coordination DockController The source’s Controller suffix makes this role explicit.
Receives callback-driven events CameraCaptureDelegate, DockAccessoryTrackingDelegate, MovieCaptureDelegate The source’s Delegate suffix makes this role explicit.
Feature data or observable state CameraModel, DockControllerModel, PreviewCameraModel, PreviewDockControllerModel The source’s Model suffix makes this role explicit.
Framework-facing operations CaptureService, DockControlService, OutputService The source’s Service suffix makes this role explicit.
User-interface presentation and input forwarding BatteryView, ChevronView, ConnectionView, ContentView The source’s View suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization DockKitCamera/Model/DockAccessoryController.swift:16 A controller is the verified coordination boundary; this is MVC-style only where a separate model is present.
Protocol-oriented abstraction DockKitCamera/Camera/MovieCapture.swift:12 A local protocol and concrete conformance create an explicit capability boundary.
Delegate or data-source callbacks DockKitCamera/Camera/MovieCapture.swift:116 Callback protocols invert event delivery back into the sample’s owner.
Service object DockKitCamera/CaptureService.swift:15 A role-named service contains framework-facing operations.
Publisher-backed observable state DockKitCamera/Camera/MovieCapture.swift:15 Published properties notify observers while mutation remains with the state object.
Actor isolation DockKitCamera/CaptureService.swift:15 A declared actor creates an explicit isolation boundary; its executor is not described as a background thread.

Main application flow

Reference code

DockKitCamera/DockControlService.swift:260animate()

    func animate(_ animation: Animation) async -> Bool {
// ...
#if !targetEnvironment(simulator)
        guard let dockkitAccessory = dockkitAccessory else {
            logger.error("No DockKit accessory connected")
            return false
        }
        if animating {
            logger.error("DockKit accessory busy animating")
            return false
        }
        do {
            animating = true
            try await DockAccessoryManager.shared.setSystemTrackingEnabled(false)
            let progress = try await dockkitAccessory.animate(motion: dockKitAnimation(from: animation))
            while !progress.isCancelled && !progress.isFinished {
                try await Task.sleep(nanoseconds: NSEC_PER_SEC / 10) // 0.1 sec
            }
            try await DockAccessoryManager.shared.setSystemTrackingEnabled(trackingMode == .system ? true : false)
        } catch {
            logger.error("Error executing animation \(animation.rawValue) : \(error)")
            try? await DockAccessoryManager.shared.setSystemTrackingEnabled(trackingMode == .system ? true : false)
            animating = false
            return false
        }
        animating = false
#endif
        return true
    }

Naming conventions

  • Types: App: DockKitCameraApp; Controller: DockController; Delegate: CameraCaptureDelegate, DockAccessoryTrackingDelegate, MovieCaptureDelegate; Model: CameraModel, DockControllerModel, PreviewCameraModel, PreviewDockControllerModel; Service: CaptureService, DockControlService, OutputService; View: BatteryView, ChevronView, ConnectionView, ContentView, PreviewView.
  • Protocols: OutputService, DockAccessoryTrackingDelegate, CameraCaptureDelegate, DockController, PreviewSource, PreviewTarget, Camera.
  • Methods: updateConfiguration, setVideoRotationAngle, getVideoRotationAngle, update, track, startOrStartCapture, switchCamera, zoom.
  • Files: DockKitCamera/Preview Content/PreviewCameraModel.swift, DockKitCamera/Views/CameraPreview.swift, DockKitCamera/CaptureService.swift, DockKitCamera/ContentView.swift, DockKitCamera/DockControlService.swift, DockKitCamera/Model/CameraModel.swift.

Architecture takeaways

  • DockKit_CameraApp is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches SwiftUI, AVFoundation, UIKit, DockKit through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
  • Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
  • Access-control conclusions separate verified language visibility from the likely design rationale.
  • Local protocol relationships provide an explicit substitution boundary.

Source map

Source file Relevant symbols
DockKitCamera/DockKit_CameraApp.swift Cited implementation, DockKitCameraApp
DockKitCamera/Model/DataTypes.swift OutputService, CameraStatus, CaptureActivity, CameraOrientation, CameraZoomType, Movie, CameraError, DockAccessoryFeatures, DockAccessoryTrackedPerson, EnabledDockKitFeatures, DockAccessoryTrackingDelegate, CameraCaptureDelegate, DockAccessoryStatus, DockAccessoryBatteryStatus, FramingMode, TrackingMode, Animation, ChevronType
DockKitCamera/Camera/DeviceLookup.swift Cited implementation, AVFoundation, Combine, DeviceLookup
DockKitCamera/Camera/MovieCapture.swift Cited implementation, DispatchQueue(label:), async declaration or closure, @Published, AnyCancellable, MovieCapture, MovieCaptureDelegate
DockKitCamera/Model/DockAccessoryController.swift DockController
DockKitCamera/CaptureService.swift CaptureService, actor, Task, @MainActor, Foundation, UIKit
DockKitCamera/ContentView.swift SwiftUI state property wrapper, SwiftUI, ContentView
DockKitCamera/Preview Content/PreviewCameraModel.swift PreviewCameraModel, PreviewSourceStub
DockKitCamera/Views/CameraPreview.swift CameraPreview, PreviewView, PreviewSource, PreviewTarget, DefaultPreviewSource
DockKitCamera/DockControlService.swift DockControlService
DockKitCamera/Model/CameraModel.swift CameraModel
DockKitCamera/Model/DockControllerModel.swift DockControllerModel
DockKitCamera/Preview Content/PreviewDockAccessoryControllerModel.swift PreviewDockControllerModel
DockKitCamera/Views/BatteryView.swift BatteryView
DockKitCamera/Views/ChevronView.swift ChevronView
DockKitCamera/Views/ConnectionView.swift ConnectionView