AVCam: Building a camera app
At a glance
| Item | Summary |
|---|---|
| Purpose | Capture photos and record video using the front and rear iPhone and iPad cameras. |
| App architecture | A Swift sample bundle with entry-bearing project variants AVCam, AVCamCaptureExtension, AVCamControlCenterExtension, each leading to AVFoundation APIs. |
| Main patterns | Protocol-oriented abstraction, Delegate or data-source callbacks, Service object, Publisher-backed observable state, Actor isolation |
| Project style | 32 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries. |
| Execution model | Source-visible boundaries: await suspension point, @MainActor, Task closure isolated to MainActor, Task, actor; none alone proves a background thread. |
| State/event model | Source-visible mechanisms: SwiftUI state property wrapper, @Observable, @Published. |
| Key frameworks/packages | SwiftUI, AVFoundation, Foundation, Combine, os; these are source dependencies, not architecture labels. |
Project structure
Source bundle/
├── AVCam/
│ ├── AVCamApp.swift
│ ├── Model/
│ │ └── DataTypes.swift
│ ├── Views/
│ │ ├── Toolbars/
│ │ │ └── MainToolbar/
│ │ │ └── CaptureButton.swift
│ │ └── CameraPreview.swift
│ ├── CameraView.swift
│ ├── CaptureService.swift
│ ├── Preview Content/
│ │ └── PreviewCameraModel.swift
│ ├── CameraModel.swift
│ └── Capture/
│ ├── PhotoCapture.swift
│ └── SPCObserver.swift
├── AVCamCaptureExtension/
│ └── AVCamCaptureExtension.swift
└── AVCamControlCenterExtension/
└── AVCamControlCenterExtensionBundle.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 5 project/configuration file(s) and 59 source declaration(s).
Overall architecture
flowchart LR
Bundle["Sample bundle"]
V1["AVCam"]
V2["AVCamCaptureExtension"]
V3["AVCamControlCenterExtension"]
Boundary["AVFoundation APIs"]
Bundle --> V1
V1 --> Boundary
Bundle --> V2
V2 --> Boundary
Bundle --> V3
V3 --> Boundary
Reference code
AVCam/AVCamApp.swift:11 — architecture anchor
@main
/// The AVCam app's main entry point.
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
The branches represent separate entry-bearing project variants in the downloaded bundle, not runtime calls between those variants. Each branch is intentionally collapsed at the documented framework boundary; the detailed target-local flow remains in the cited files. Ownership is claimed only where the next section cites a stored property or assignment.
Ownership and state
classDiagram
AVCamApp *-- CameraModel : camera
AVCamApp *-- Logger : logger
Photo *-- Data : data
Photo *-- Bool : isProxy
Ownership evidence
AVCam/AVCamApp.swift:16 — stored dependency or nearest verified ownership anchor
struct AVCamApp: App {
// ...
@State private var camera = CameraModel()
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
AVCamApp |
CameraModel (camera) |
owns wrapper-managed state | Owning lexical scope |
AVCamApp |
Logger (logger) |
creates and retains | Initialized by the owner; the binding is immutable |
Photo |
Data (data) |
owns value state | Initialized by the owner; the binding is immutable |
Photo |
Bool (isProxy) |
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 |
|---|---|---|---|
| Suspension boundary | await suspension point |
The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. | AVCam/AVCamApp.swift:27 |
| Main isolation | @MainActor |
The cited annotation marks its attached declaration or closure as main-actor isolated. | AVCam/AVCamApp.swift:33 |
| Main isolation | Task closure isolated to MainActor |
The cited operation explicitly enters a main-actor-isolated region. | AVCam/AVCamApp.swift:33 |
| Task creation | Task |
The source creates an unstructured task; surrounding context determines inherited actor isolation. | AVCam/AVCamApp.swift:33 |
| Actor isolation | actor |
The cited type is actor-isolated; this does not select a background thread. | AVCam/CaptureService.swift:14 |
@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
AVCam/AVCamApp.swift:27 — representative execution boundary
struct AVCamApp: App {
// ...
await camera.start()
// ...
}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 | SwiftUI state property wrapper |
A SwiftUI property wrapper supplies or observes UI state. | AVCam/AVCamApp.swift:16 |
| State propagation | @Observable |
Observation macro publishes source-visible changes. | AVCam/CameraModel.swift:21 |
| State propagation | @Published |
A published property can emit owner-controlled changes. | AVCam/Capture/MovieCapture.swift:15 |
| Source import | SwiftUI |
The cited file imports this module; runtime use and architectural role are not inferred. | AVCam/AVCamApp.swift:9 |
| Source import | AVFoundation |
The cited file imports this module; runtime use and architectural role are not inferred. | AVCam/CameraModel.swift:10 |
| Source import | Foundation |
The cited file imports this module; runtime use and architectural role are not inferred. | AVCam/CaptureService.swift:8 |
| Source import | Combine |
The cited file imports this module; runtime use and architectural role are not inferred. | AVCam/CameraModel.swift:9 |
| Source import | os |
The cited file imports this module; runtime use and architectural role are not inferred. | AVCam/AVCamApp.swift:8 |
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
AVCam/Model/DataTypes.swift:147 — representative type boundary
protocol OutputService {
associatedtype Output: AVCaptureOutput
// ...
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
AVCamApp |
Application entry and top-level composition | App |
OutputService |
Defines a capability or collaboration contract | Concrete collaborators/imported frameworks |
PlatformView |
Defines a capability or collaboration contract | View |
CameraView |
User-interface presentation and input forwarding | Concrete collaborators/imported frameworks |
CaptureService |
Framework-facing operations | Concrete collaborators/imported frameworks |
CaptureControlsDelegate |
Receives callback-driven events | NSObject, AVCaptureSessionControlsDelegate |
PreviewCameraModel |
Feature data or observable state | Camera |
PreviewView |
User-interface presentation and input forwarding | UIView, PreviewTarget |
CameraModel |
Feature data or observable state | Camera |
ReadinessDelegate |
Receives callback-driven events | NSObject, AVCapturePhotoOutputReadinessCoordinatorDelegate |
The source explicitly defines local protocol relationships: CameraModel → Camera, MovieCapture → OutputService, PhotoCapture → OutputService, PreviewCameraModel → Camera, PreviewSourceStub → PreviewSource, PreviewView → PreviewTarget.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
camera (AVCam/AVCamApp.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. |
status (AVCam/CameraModel.swift:25) |
private(set) |
Read access follows the declaration; writes remain in the private scope. | Inference: allow observation while reserving invariant-changing writes for the owner. |
captureActivity (AVCam/CameraModel.swift:28) |
private(set) |
Read access follows the declaration; writes remain in the private scope. | Inference: allow observation while reserving invariant-changing writes for the owner. |
isSwitchingVideoDevices (AVCam/CameraModel.swift:31) |
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
AVCam/AVCamApp.swift:16 — representative boundary
struct AVCamApp: App {
// ...
@State private var camera = CameraModel()
// ...
}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 | AVCamApp |
The source’s App suffix makes this role explicit. |
| Receives callback-driven events | CaptureControlsDelegate, MovieCaptureDelegate, PhotoCaptureDelegate, ReadinessDelegate |
The source’s Delegate suffix makes this role explicit. |
| Feature data or observable state | CameraModel, PreviewCameraModel |
The source’s Model suffix makes this role explicit. |
| Observes and relays feature changes | SystemPreferredCameraObserver |
The source’s Observer suffix makes this role explicit. |
| Framework-facing operations | CaptureService, OutputService |
The source’s Service suffix makes this role explicit. |
| User-interface presentation and input forwarding | CameraView, CaptureModeView, PlatformView, PreviewView |
The source’s View suffix makes this role explicit. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Protocol-oriented abstraction | AVCam/CameraModel.swift:22 |
A local protocol and concrete conformance create an explicit capability boundary. |
| Delegate or data-source callbacks | AVCam/Capture/MovieCapture.swift:77 |
Callback protocols invert event delivery back into the sample’s owner. |
| Service object | AVCam/CaptureService.swift:14 |
A role-named service contains framework-facing operations. |
| Publisher-backed observable state | AVCam/Capture/MovieCapture.swift:15 |
Published properties notify observers while mutation remains with the state object. |
| Actor isolation | AVCam/CaptureService.swift:14 |
A declared actor creates an explicit isolation boundary; its executor is not described as a background thread. |
Main application flow
sequenceDiagram
actor User
participant View as CameraView
participant Model as CameraModel
participant Service as CaptureService
participant Photo as PhotoCapture
participant Library as MediaLibrary
User->>View: Tap shutter
View->>Model: capturePhoto()
Model->>Service: capturePhoto(features)
Service->>Photo: capturePhoto(features)
Photo-->>Model: Photo
Model->>Library: save(photo)
Library-->>Model: thumbnail stream update
Model-->>View: observable thumbnail/activity
Reference code
AVCam/CameraModel.swift:154 — capturePhoto
func capturePhoto() async {
do {
let photo = try await captureService.capturePhoto(with: currentPhotoFeatures)
try await mediaLibrary.save(photo: photo)
} catch {
self.error = error
}
}Naming conventions
- Types: App: AVCamApp; Delegate: CaptureControlsDelegate, MovieCaptureDelegate, PhotoCaptureDelegate, ReadinessDelegate; Model: CameraModel, PreviewCameraModel; Observer: SystemPreferredCameraObserver; Service: CaptureService, OutputService; View: CameraView, CaptureModeView, PlatformView, PreviewView, RecordingTimeView.
- Protocols:
OutputService,PlatformView,PreviewSource,PreviewTarget,Camera. - Methods:
updateConfiguration,setVideoRotationAngle,makeBody,start,setUpSession,addInput,addOutput,configureControls. - Files:
AVCam/AVCamApp.swift,AVCamCaptureExtension/AVCamCaptureExtension.swift,AVCamControlCenterExtension/AVCamControlCenterExtensionBundle.swift,AVCam/Views/Toolbars/MainToolbar/CaptureButton.swift,AVCam/CameraView.swift,AVCam/CaptureService.swift.
Architecture takeaways
AVCamAppis the main source-visible entry or composition anchor for this sample.- Framework work reaches SwiftUI, AVFoundation, AppIntents, LockedCameraCapture 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 |
|---|---|
AVCam/AVCamApp.swift |
Cited implementation, await suspension point, @MainActor, Task closure isolated to MainActor, Task, SwiftUI state property wrapper, SwiftUI, os, AVCamApp |
AVCam/Model/DataTypes.swift |
OutputService, CameraStatus, CaptureActivity, CaptureMode, Photo, Movie, PhotoFeatures, CaptureCapabilities, QualityPrioritization, CameraError |
AVCam/CameraModel.swift |
Cited implementation, @Observable, AVFoundation, Combine, CameraModel |
AVCam/Capture/MovieCapture.swift |
Cited implementation, @Published, MovieCapture, MovieCaptureDelegate |
AVCam/CaptureService.swift |
CaptureService, actor, Foundation, CaptureControlsDelegate |
AVCamCaptureExtension/AVCamCaptureExtension.swift |
AVCamCaptureExtension |
AVCamControlCenterExtension/AVCamControlCenterExtensionBundle.swift |
AVCamControlCenterExtensionBundle |
AVCam/Views/Toolbars/MainToolbar/CaptureButton.swift |
CaptureButton, PhotoCaptureButton, PhotoButtonStyle, MovieCaptureButton, NoFadeButtonStyle, BusyShutterButton |
AVCam/CameraView.swift |
CameraView, SwipeDirection |
AVCam/Preview Content/PreviewCameraModel.swift |
PreviewCameraModel, PreviewSourceStub |
AVCam/Views/CameraPreview.swift |
CameraPreview, PreviewView, PreviewSource, PreviewTarget, DefaultPreviewSource |
AVCam/Capture/PhotoCapture.swift |
PhotoCaptureError, PhotoCapture, ReadinessDelegate, PhotoCaptureDelegate |
AVCam/Capture/SPCObserver.swift |
SystemPreferredCameraObserver |
AVCam/Support/ViewExtensions.swift |
PlatformView, AdaptiveToolbar, DefaultButtonStyle, Size |
AVCam/Views/Controls/CaptureModeView.swift |
CaptureModeView |
AVCam/Views/Overlays/RecordingTimeView.swift |
RecordingTimeView |