AVCam: Building a camera app
At a glance
| Item | Summary |
|---|---|
| Purpose | Capture photos and record video with the front, rear, and external cameras, then save the media to the Photos library. |
| App architecture | SwiftUI views depend on a @MainActor Camera protocol. CameraModel implements it and drives two actors: CaptureService, which owns the AVCaptureSession and its outputs, and MediaLibrary, which writes to Photos. |
| Main patterns | Actor isolation (a capture actor with a custom serial executor), protocol-oriented abstraction (Camera, OutputService, PreviewSource/PreviewTarget), delegate callbacks bridged to continuations and streams, and @Published state read as async sequences. |
| Project style | One Xcode project with three targets: the app, a Locked Camera Capture extension, and a Control Center extension. App sources are grouped into Capture/, Model/, Views/, and Support/. |
| Execution model | CameraModel is @MainActor. CaptureService is an actor whose executor is the serial DispatchSerialQueue sessionQueue. MediaLibrary is an actor with the default executor. |
| State/event model | @Observable model properties drive SwiftUI. Actor and output @Published properties reach the model through .values loops. Delegate callbacks resume checked continuations or yield into AsyncStreams. |
| Key frameworks/packages | AVFoundation, SwiftUI, Combine, Photos, LockedCameraCapture, AppIntents, WidgetKit, ExtensionKit. The project declares no Swift package. |
Platform boundary
The DocC record lists iOS, iPadOS, and Mac Catalyst. In the downloaded project, the targets set SDKROOT = iphoneos and SUPPORTS_MACCATALYST = NO (AVCam.xcodeproj/project.pbxproj:945) with an iOS 26.0 deployment target (AVCam.xcodeproj/project.pbxproj:936). The README asks for a physical iOS device because Simulator has no cameras (README.md:16).
Project structure
AVCam.xcodeproj/ 3 native targets, no Swift packages
AVCam/
├── AVCamApp.swift @main App; creates CameraModel
├── CameraModel.swift @MainActor @Observable; implements Camera
├── CameraView.swift root view, generic over Camera
├── CaptureService.swift actor; session, inputs, outputs, controls
├── Capture/
│ ├── PhotoCapture.swift OutputService for AVCapturePhotoOutput
│ ├── MovieCapture.swift OutputService for AVCaptureMovieFileOutput
│ ├── DeviceLookup.swift discovery sessions
│ └── SPCObserver.swift system-preferred camera KVO → AsyncStream
├── Model/
│ ├── Camera.swift view-facing protocol
│ ├── CameraState.swift persisted state shared with the extension
│ ├── DataTypes.swift value types, OutputService protocol
│ ├── MediaLibrary.swift actor; Photos writes and thumbnails
│ └── Intent/AVCamCaptureIntent.swift
├── Preview Content/PreviewCameraModel.swift
├── Support/ View and capture extensions
└── Views/ CameraPreview, PreviewContainer, CameraUI, toolbars, overlays
AVCamCaptureExtension/ LockedCameraCaptureExtension entry
AVCamControlCenterExtension/ ControlWidget and bundle
Structure observations
- The project has three native targets:
AVCamCaptureExtension(ExtensionKit extension),AVCamControlCenterExtension(app extension), andAVCam(application) (AVCam.xcodeproj/project.pbxproj:407,AVCam.xcodeproj/project.pbxproj:427,AVCam.xcodeproj/project.pbxproj:448). - The capture extension reuses the app’s model and root view. It creates its own
CameraModeland starts it the same way the app does (AVCamCaptureExtension/AVCamCaptureExtension.swift:17,AVCamCaptureExtension/AVCamCaptureExtension.swift:25). - Capture code is split by output.
CaptureServiceorchestrates the session, whilePhotoCaptureandMovieCaptureeach wrap one AVFoundation output behindOutputService(AVCam/Model/DataTypes.swift:143). - Views never import the capture actor. They receive a
Cameraand aPreviewSource(AVCam/Views/CameraPreview.swift:79).
Overall architecture
flowchart LR
App["AVCamApp / AVCamCaptureExtension"] --> Model["CameraModel (@MainActor)"]
App --> View["CameraView<Camera>"]
View --> Model
Model --> Service["CaptureService actor"]
Model --> Library["MediaLibrary actor"]
Service --> Session["AVCaptureSession"]
Service --> Outputs["PhotoCapture / MovieCapture"]
Service -. "nonisolated previewSource" .-> Preview["CameraPreview / PreviewView"]
Library --> Photos["PHPhotoLibrary"]
Reference code
AVCam/AVCamApp.swift:13 — app composition
struct AVCamApp: App {
// Simulator doesn't support the AVFoundation capture APIs. Use the preview camera when running in Simulator.
@State private var camera = CameraModel()
// An indication of the scene's operational state.
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
CameraView(camera: camera)
.statusBarHidden(true)
.task {
// Start the capture pipeline.
await camera.start()
}
// Monitor the scene phase. Synchronize the persistent state when
// the camera is running and the app becomes active.
.onChange(of: scenePhase) { _, newPhase in
guard camera.status == .running, newPhase == .active else { return }
Task { @MainActor in
await camera.syncState()
}
}
}
}
}Interpretation
Observed: the app root creates one CameraModel, passes it to CameraView as an initializer argument, and starts the pipeline from .task. CameraModel creates the two actors (AVCam/CameraModel.swift:54, AVCam/CameraModel.swift:57). The only capture object that reaches the views is the preview source, exposed as a nonisolated let (AVCam/CaptureService.swift:28). The source comment at line 15 mentions a preview camera for Simulator, but the property is initialized with CameraModel(). PreviewCameraModel is used only by #Preview blocks (AVCam/CameraView.swift:76).
Inference: the layering is UI → main-actor model → capture actor → AVFoundation. The model translates view intent into actor calls and actor state into observable properties.
Ownership and state
classDiagram
AVCamApp *-- CameraModel : @State camera
AVCamCaptureExtension *-- CameraModel : @State camera
CameraModel *-- CaptureService : private let
CameraModel *-- MediaLibrary : private let
CameraModel *-- CameraState : private var
CaptureService *-- AVCaptureSession : private let
CaptureService *-- PhotoCapture : private let
CaptureService *-- MovieCapture : private let
CaptureService *-- DeviceLookup : private let
CaptureService *-- CaptureControlsDelegate : private var
CameraView o-- CameraModel : @State camera
Ownership evidence
AVCam/CameraModel.swift:54 — the model creates and retains its collaborators
private let mediaLibrary = MediaLibrary()
/// An object that manages the app's capture functionality.
private let captureService = CaptureService()
/// Persistent state shared between the app and capture extension.
private var cameraState = CameraState()| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
AVCamApp |
CameraModel |
Creates it in @State private var camera (AVCam/AVCamApp.swift:16) |
CameraModel |
CameraModel |
status, captureActivity, thumbnail, error, switching flags |
private(set) var (AVCam/CameraModel.swift:24, AVCam/CameraModel.swift:42) |
CameraModel, on the main actor |
CameraModel |
captureMode, isLivePhotoEnabled, qualityPrioritization, isHDRVideoEnabled |
Settable through Camera. Their didSet observers write cameraState and, where needed, call the actor (AVCam/CameraModel.swift:101) |
Views write; CameraModel reacts |
CameraModel |
CameraState |
Stored value. Each property’s didSet calls save(), which updates the capture intent’s app context (AVCam/Model/CameraState.swift:33) |
CameraModel |
CaptureService |
AVCaptureSession, PhotoCapture, MovieCapture, DeviceLookup |
private let (AVCam/CaptureService.swift:31, AVCam/CaptureService.swift:34, AVCam/CaptureService.swift:37, AVCam/CaptureService.swift:49) |
Only the actor |
CaptureService |
activeVideoInput, rotationCoordinator, controlsMap |
private var (AVCam/CaptureService.swift:43, AVCam/CaptureService.swift:55, AVCam/CaptureService.swift:65) |
Only the actor |
PhotoCapture |
One PhotoCaptureDelegate per capture |
Created in capturePhoto(with:). AVFoundation holds it during the capture; PhotoCapture does not store it (AVCam/Capture/PhotoCapture.swift:43) |
The delegate resumes the continuation |
MovieCapture |
Current MovieCaptureDelegate |
Stored in private var delegate (AVCam/Capture/MovieCapture.swift:23), replaced on each recording (AVCam/Capture/MovieCapture.swift:44) |
MovieCapture |
MediaLibrary |
Thumbnail stream continuation | private let continuation (AVCam/Model/MediaLibrary.swift:23) |
Only the actor yields |
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 |
|---|---|---|---|
| Main-actor isolation | @MainActor final class CameraModel, @MainActor protocol Camera |
All view-facing state and its mutation | AVCam/CameraModel.swift:19, AVCam/Model/Camera.swift:14 |
| Actor executor | actor CaptureService whose unownedExecutor returns sessionQueue.asUnownedSerialExecutor() |
Session configuration, startRunning(), device changes, and focus run as jobs on the serial sessionQueue |
AVCam/CaptureService.swift:68, AVCam/CaptureService.swift:71 |
| Framework callbacks on the actor’s queue | setControlsDelegate(_:queue: sessionQueue), lensSlider.setActionQueue(sessionQueue) |
Camera Control callbacks and slider actions are delivered on the same queue that backs the actor | AVCam/CaptureService.swift:224, AVCam/CaptureService.swift:243 |
| Second actor | actor MediaLibrary |
Photos authorization, writes, and thumbnail yields; default executor | AVCam/Model/MediaLibrary.swift:13 |
| Start-up task | .task { await camera.start() } |
SwiftUI creates the task and ties it to the root view’s lifetime | AVCam/AVCamApp.swift:25 |
| Unretained main-actor tasks | Four Task { for await ... } loops in observeState() |
Thumbnails, capture activity, capabilities, and fullscreen-controls state. The tasks are not stored, so nothing cancels them. | AVCam/CameraModel.swift:198 |
| Unretained actor tasks | Notification loops and monitorSystemPreferredCamera() |
Each loop body mutates actor state without await, so it inherits CaptureService isolation |
AVCam/CaptureService.swift:359, AVCam/CaptureService.swift:552 |
| Retained, cancellable task | subjectAreaChangeTask?.cancel(), then a new Task |
The only stored task; replaced when the device changes | AVCam/CaptureService.swift:443, AVCam/CaptureService.swift:452 |
| Caller-isolation inheritance | monitorProgress(of:isolation: isolated (any Actor)? = #isolation) |
The photo-progress task runs in the calling actor’s isolation and mutates livePhotoCount |
AVCam/Capture/PhotoCapture.swift:89 |
| Main-actor hops | Task { @MainActor in ... } |
Preview-layer session assignment and preview rotation | AVCam/Views/CameraPreview.swift:66, AVCam/CaptureService.swift:405 |
| Main run-loop timer | Timer.publish(every:on: .main, in: .common) |
Recording-duration ticks. The stored cancellable is cancelled on stop. | AVCam/Capture/MovieCapture.swift:84, AVCam/Capture/MovieCapture.swift:96 |
| Compiler checking level | SWIFT_STRICT_CONCURRENCY = minimal, @preconcurrency import AVFoundation |
The compiler does not fully check these crossings | AVCam.xcodeproj/project.pbxproj:949, AVCam/CaptureService.swift:9 |
Reference code
AVCam/CaptureService.swift:68 — the actor runs on its session queue
private let sessionQueue = DispatchSerialQueue(label: "com.example.apple-samplecode.AVCam.sessionQueue")
// Sets the session queue as the actor's executor.
nonisolated var unownedExecutor: UnownedSerialExecutor {
sessionQueue.asUnownedSerialExecutor()
}Observed: the README states that configuring and starting a session are blocking operations and that the actor keeps them off the main thread (README.md:13). The custom executor is the code that places that work on sessionQueue. Because the controls delegate and slider actions also use sessionQueue, framework callbacks and actor jobs share one serial queue.
Inference: PhotoCapture and MovieCapture are plain classes without their own isolation. They are mutated safely only because CaptureService is their sole owner and calls them from its isolation. MovieCapture’s timer sink writes captureActivity from the main run loop, outside that isolation (AVCam/Capture/MovieCapture.swift:90), and the minimal checking level does not flag it.
Session start-up
AVCam/CaptureService.swift:137 — deferred start during setup
// Deferred start brings up the preview first, and prepares the capture outputs a moment
// later. An app that links the iOS 26 SDK gets this behavior by default; these
// assignments show the properties that control it.
captureSession.automaticallyRunsDeferredStart = true
// Add the photo capture output as the default output type.
photoCapture.output.isDeferredStartEnabled = photoCapture.output.isDeferredStartSupported
try addOutput(photoCapture.output)The views pair this with View.hidden(until:) (AVCam/Support/ViewExtensions.swift:64), which keeps the thumbnail, camera-switch, mode, and feature controls at zero opacity until status == .running. The shutter is not gated. The source comment relies on responsive capture to honor an early tap (AVCam/Views/Toolbars/MainToolbar/MainToolbar.swift:27).
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 |
|---|---|---|---|
| Model to views | @Observable CameraModel, held as @State var camera in generic views |
Views read model properties and call its async methods | AVCam/CameraModel.swift:20, AVCam/CameraView.swift:18 |
| Actor to model | @Published private(set) on the actor, read through .values |
Capture activity, capabilities, and the fullscreen-controls flag reach the model | AVCam/CaptureService.swift:17, AVCam/CameraModel.swift:207 |
| Outputs to actor | Publishers.Merge(...).assign(to: &$captureActivity) |
Combines photo and movie activity into one actor property | AVCam/CaptureService.swift:540 |
| Delegate to actor | controlsDelegate.$isShowingFullscreenControls.assign(to:) |
Camera Control appearance reaches the actor | AVCam/CaptureService.swift:546 |
| Library to model | AsyncStream<CGImage?> thumbnails |
MediaLibrary yields a thumbnail after each save |
AVCam/Model/MediaLibrary.swift:22, AVCam/CameraModel.swift:200 |
| System events | NotificationCenter.notifications(named:) async sequences |
Interruptions, runtime errors, and subject-area changes | AVCam/CaptureService.swift:553, AVCam/CaptureService.swift:446 |
| KVO to stream | SystemPreferredCameraObserver.changes |
The system-preferred camera switches the active device | AVCam/Capture/SPCObserver.swift:25, AVCam/CaptureService.swift:361 |
| App/extension state | CameraState stored as the AVCamCaptureIntent app context |
Shared settings between the app and the capture extension | AVCam/Model/CameraState.swift:36, AVCam/Model/Intent/AVCamCaptureIntent.swift:15 |
| Framework import | SwiftUI, Combine only, in CameraModel.swift |
The model file does not import AVFoundation | AVCam/CameraModel.swift:8, AVCam/CameraModel.swift:9 |
| Framework import | @preconcurrency import AVFoundation |
Capture and preview code | AVCam/CaptureService.swift:9, AVCam/Views/CameraPreview.swift:9 |
| Framework import | Photos |
Media library writes | AVCam/Model/MediaLibrary.swift:9 |
| Framework import | LockedCameraCapture, ExtensionKit |
Capture-extension entry point | AVCamCaptureExtension/AVCamCaptureExtension.swift:8, AVCamCaptureExtension/AVCamCaptureExtension.swift:10 |
| Framework import | WidgetKit, AppIntents |
Control Center button that runs the capture intent | AVCamControlCenterExtension/AVCamControlCenterExtension.swift:9, AVCamControlCenterExtension/AVCamControlCenterExtension.swift:20 |
Combine scheduling: the source never calls receive(on:) or subscribe(on:). Delivery into the model happens inside main-actor tasks that iterate .values.
Class and protocol design
classDiagram
class Camera {
<<protocol>>
}
class OutputService {
<<protocol>>
output
updateConfiguration(device)
}
class PreviewSource {
<<protocol>>
}
class PreviewTarget {
<<protocol>>
}
CameraModel ..|> Camera
PreviewCameraModel ..|> Camera
PhotoCapture ..|> OutputService
MovieCapture ..|> OutputService
DefaultPreviewSource ..|> PreviewSource
PreviewView ..|> PreviewTarget
CameraView --> Camera : generic parameter
CaptureService --> OutputService : fan-out
Reference code
AVCam/Model/DataTypes.swift:143 — the per-output contract and its defaults
protocol OutputService {
associatedtype Output: AVCaptureOutput
var output: Output { get }
var captureActivity: CaptureActivity { get }
var capabilities: CaptureCapabilities { get }
func updateConfiguration(for device: AVCaptureDevice)
func setVideoRotationAngle(_ angle: CGFloat)
}
extension OutputService {
func setVideoRotationAngle(_ angle: CGFloat) {
// Set the rotation angle on the output object's video connection.
output.connection(with: .video)?.videoRotationAngle = angle
}
func updateConfiguration(for device: AVCaptureDevice) {}
}| Type | Responsibility | Depends on |
|---|---|---|
Camera (protocol) |
View-facing contract for status, capture actions, and settings | Value types in DataTypes.swift |
CameraModel |
Translates view intent into actor calls and persists settings | CaptureService, MediaLibrary, CameraState |
CaptureService (actor) |
Session setup, mode and device changes, rotation, focus, Camera Control | AVCaptureSession, OutputService conformers, DeviceLookup |
PhotoCapture / MovieCapture |
One output each; expose activity and capabilities | OutputService |
MediaLibrary (actor) |
Photos authorization, asset creation, thumbnails | PHPhotoLibrary, CLLocationUpdate |
PreviewSource / PreviewTarget |
Connect the session to the preview layer without exposing it to views | AVCaptureSession |
Observed: CaptureService keeps outputServices as [any OutputService] and calls updateConfiguration(for:) and setVideoRotationAngle(_:) on each element (AVCam/CaptureService.swift:40, AVCam/CaptureService.swift:413, AVCam/CaptureService.swift:527). MovieCapture uses that hook to prepare HEVC settings and video stabilization before recording starts (AVCam/Capture/MovieCapture.swift:107). Views are generic over Camera rather than using an existential (AVCam/CameraView.swift:13).
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
CameraModel.status and other state (AVCam/CameraModel.swift:24) |
private(set) |
Views read but cannot write | Inference: only the model’s own flows change observable state. |
CameraModel.captureService, mediaLibrary (AVCam/CameraModel.swift:54, AVCam/CameraModel.swift:57) |
private |
Views cannot reach the actors | Inference: the Camera protocol is the only UI entry point. |
CaptureService.captureActivity, captureCapabilities, isInterrupted (AVCam/CaptureService.swift:17) |
@Published private(set) |
The model can observe but not write | Inference: the actor stays the single writer. |
CaptureService.captureSession (AVCam/CaptureService.swift:31) |
private let |
Only the actor configures the session | Inference: all session mutation goes through the actor’s queue. |
CaptureService.previewSource (AVCam/CaptureService.swift:28) |
implicit internal, nonisolated let |
Readable synchronously from main-actor views | Inference: the preview attaches without an actor hop. |
PhotoCaptureDelegate (AVCam/Capture/PhotoCapture.swift:142) |
private class |
Visible only in PhotoCapture.swift |
Inference: the delegate is an implementation detail of the async API. |
MovieCapture.MovieCaptureDelegate (AVCam/Capture/MovieCapture.swift:64) |
private class, nested |
Visible only inside MovieCapture |
Same as above. |
CameraState.save() (AVCam/Model/CameraState.swift:33) |
private |
Persistence happens only through property didSet |
Inference: callers cannot skip or duplicate the save. |
Reference code
AVCam/CaptureService.swift:14 — published state with private writes
actor CaptureService {
/// A value that indicates whether the capture service is idle or capturing a photo or movie.
@Published private(set) var captureActivity: CaptureActivity = .idle
/// A value that indicates the current capture capabilities of the service.
@Published private(set) var captureCapabilities = CaptureCapabilities.unknown
/// A Boolean value that indicates whether a higher priority event, like receiving a phone call, interrupts the app.
@Published private(set) var isInterrupted = false
// ...
}Most other declarations use Swift’s implicit internal. The private and private(set) modifiers above are the boundaries that matter.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Session configuration and start | CaptureService.setUpSession(), start(with:) |
Runs on sessionQueue (AVCam/CaptureService.swift:113). |
| Mode switching | CaptureService.setCaptureMode(_:) |
Adds or removes the movie output inside one begin/commit pair (AVCam/CaptureService.swift:269). |
| Device switching | CaptureService.changeCaptureDevice(to:) |
Replaces the input, controls, rotation coordinator, and capabilities together, and restores the old input on failure (AVCam/CaptureService.swift:325). |
| Photo settings | PhotoCapture.createPhotoSettings(with:) |
Built per capture from PhotoFeatures (AVCam/Capture/PhotoCapture.swift:54). |
| Recording duration | MovieCapture.startMonitoringDuration() |
Polls recordedDuration on a timer (AVCam/Capture/MovieCapture.swift:82). |
| Saving and thumbnails | MediaLibrary.performChange(_:) |
One shared path for photo and movie writes (AVCam/Model/MediaLibrary.swift:89). |
| Persisted settings | CameraState |
Saved to the capture intent’s app context for the extension (AVCam/Model/CameraState.swift:36). |
| Launch and resume polish | View.hidden(until:), PreviewContainer.updateCoverOpacity(_:_:) |
View-only concerns keyed to status and scenePhase (AVCam/Views/PreviewContainer.swift:81). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Actor isolation | actor CaptureService with a sessionQueue executor (AVCam/CaptureService.swift:14, AVCam/CaptureService.swift:71); actor MediaLibrary (AVCam/Model/MediaLibrary.swift:13) |
Keeps blocking session work and Photos writes off the main actor |
| Protocol-oriented abstraction | Camera (AVCam/Model/Camera.swift:15) with CameraModel and PreviewCameraModel; OutputService (AVCam/Model/DataTypes.swift:143); PreviewSource (AVCam/Views/CameraPreview.swift:79) |
Views can be previewed with a stub model. Output configuration fans out through one contract. |
| Delegate or data-source callbacks | PhotoCaptureDelegate (AVCam/Capture/PhotoCapture.swift:142), MovieCaptureDelegate (AVCam/Capture/MovieCapture.swift:64), CaptureControlsDelegate (AVCam/CaptureService.swift:582) |
AVFoundation callbacks are bridged into continuations, streams, or @Published values |
| Publisher-backed observable state | @Published private(set) on the actor and output wrappers, consumed through .values (AVCam/CameraModel.swift:207) |
The capture layer publishes and the main-actor model iterates; only the owner writes |
No MVVM, Coordinator, or Service-object label is claimed. CameraModel is the view-facing model, but the source does not separate per-screen view models.
Main application flow
sequenceDiagram
actor User
participant Button as CaptureButton
participant Model as CameraModel
participant Service as CaptureService
participant Photo as PhotoCapture
participant Delegate as PhotoCaptureDelegate
participant Library as MediaLibrary
User->>Button: Tap shutter
Button->>Model: Task { await capturePhoto() }
Model->>Service: await capturePhoto(with: features)
Service->>Photo: await capturePhoto(with: features)
Photo->>Delegate: photoOutput.capturePhoto(with:delegate:)
Delegate-->>Photo: continuation.resume(returning: photo)
Photo-->>Model: Photo
Model->>Library: await save(photo:)
Library-->>Model: thumbnails stream yields
Reference code
AVCam/CameraModel.swift:125 — the model builds features, captures, and saves
func capturePhoto() async {
do {
let photoFeatures = PhotoFeatures(isLivePhotoEnabled: isLivePhotoEnabled, qualityPrioritization: qualityPrioritization)
let photo = try await captureService.capturePhoto(with: photoFeatures)
try await mediaLibrary.save(photo: photo)
} catch {
self.error = error
}
}AVCam/CaptureService.swift:482 — the actor forwards to the photo output wrapper
func capturePhoto(with features: PhotoFeatures) async throws -> Photo {
try await photoCapture.capturePhoto(with: features)
}AVCam/Capture/PhotoCapture.swift:36 — the delegate API becomes one async call
func capturePhoto(with features: PhotoFeatures) async throws -> Photo {
// Wrap the delegate-based capture API in a continuation to use it in an async context.
try await withCheckedThrowingContinuation { continuation in
// Create a settings object to configure the photo capture.
let photoSettings = createPhotoSettings(with: features)
let delegate = PhotoCaptureDelegate(continuation: continuation)
monitorProgress(of: delegate)
// Capture a new photo with the specified settings.
photoOutput.capturePhoto(with: photoSettings, delegate: delegate)
}
}AVCam/Capture/PhotoCapture.swift:206 — the final callback resumes the continuation
func photoOutput(_ output: AVCapturePhotoOutput, didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) {
// ...
/// Create a photo object to save to the `MediaLibrary`.
let photo = Photo(data: photoData, isProxy: isProxyPhoto, livePhotoMovieURL: livePhotoMovieURL)
// Resume the continuation by returning the captured photo.
continuation.resume(returning: photo)
}Observed: while the capture runs, the delegate also yields CaptureActivity values into its activityStream. monitorProgress forwards them to PhotoCapture.captureActivity, which reaches the model through the merged publisher.
Naming conventions
- Types: role nouns.
CaptureService(actor),CameraModel,MediaLibrary,PhotoCapture/MovieCaptureoutput wrappers,DeviceLookup,SystemPreferredCameraObserver, and AVFoundation adopters ending inDelegate. - Protocols:
Cameranames the view-facing capability.OutputService,PreviewSource, andPreviewTargetname collaborator roles. - Methods: lifecycle verbs (
start,setUpSession,syncState,observeState,updateConfiguration(for:)), commands (capturePhoto,toggleRecording,switchVideoDevices,focusAndExpose(at:)), and observation setup prefixedobserve/monitor. Booleans useis…,prefers…, andshould…. - Files and extensions: one primary type per file. Folders separate capture, model, views, and support code. Simulator and preview stubs live in
Preview Content/.
Architecture takeaways
- Put blocking framework work in an actor and give it an explicit serial executor. Route the framework’s own callback queues to the same queue.
- A
@MainActorprotocol between views and the model lets SwiftUI previews substitute a stub (PreviewCameraModel) without touching capture code. - Wrap each AVFoundation output in its own type behind a small protocol, and let the orchestrating actor fan configuration out to all of them.
- Bridge delegate APIs to
asyncwith a per-call delegate that owns a checked continuation and anAsyncStreamfor progress. - Task lifetimes are mostly implicit. The start-up task belongs to SwiftUI’s
.task, the observation loops are unretained, and onlysubjectAreaChangeTaskis stored and cancelled.
Source map
| Source file | Relevant symbols |
|---|---|
AVCam/AVCamApp.swift |
AVCamApp |
AVCam/CameraModel.swift |
CameraModel, start(), capturePhoto(), observeState() |
AVCam/CaptureService.swift |
CaptureService, sessionQueue, unownedExecutor, setUpSession(), setCaptureMode(_:), changeCaptureDevice(to:), CaptureControlsDelegate |
AVCam/Capture/PhotoCapture.swift |
PhotoCapture, createPhotoSettings(with:), monitorProgress(of:isolation:), PhotoCaptureDelegate |
AVCam/Capture/MovieCapture.swift |
MovieCapture, MovieCaptureDelegate, updateConfiguration(for:) |
AVCam/Capture/SPCObserver.swift |
SystemPreferredCameraObserver |
AVCam/Model/Camera.swift |
Camera |
AVCam/Model/CameraState.swift |
CameraState |
AVCam/Model/DataTypes.swift |
OutputService, PhotoFeatures, CaptureCapabilities |
AVCam/Model/MediaLibrary.swift |
MediaLibrary, performChange(_:) |
AVCam/Model/Intent/AVCamCaptureIntent.swift |
AVCamCaptureIntent |
AVCam/CameraView.swift |
CameraView |
AVCam/Views/CameraPreview.swift |
CameraPreview, PreviewView, PreviewSource, PreviewTarget, DefaultPreviewSource |
AVCam/Views/PreviewContainer.swift |
PreviewContainer, updateCoverOpacity(_:_:) |
AVCam/Views/Toolbars/MainToolbar/MainToolbar.swift |
MainToolbar |
AVCam/Support/ViewExtensions.swift |
PlatformView, View.hidden(until:) |
AVCamCaptureExtension/AVCamCaptureExtension.swift |
AVCamCaptureExtension |
AVCamControlCenterExtension/AVCamControlCenterExtension.swift |
AVCamControlCenterExtension |
AVCam.xcodeproj/project.pbxproj |
Targets, SWIFT_STRICT_CONCURRENCY, SUPPORTS_MACCATALYST |
README.md |
Actor rationale, device requirement |