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

Capturing consistent color images

At a glance

Item Summary
Purpose Add the power of a photography studio and lighting rig to your app with the new Constant Color API.
App architecture A Swift sample with the source-visible chain ConstantColorCamAppContentViewDataModelSwiftUI / Photos APIs.
Main patterns Delegate or data-source callbacks, Binding-based state propagation
Project style 8 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, Task, @MainActor, Task closure isolated to MainActor; none alone proves a background thread.
State/event model Source-visible mechanisms: SwiftUI state property wrapper, @Observable.
Key frameworks/packages SwiftUI, Photos, os, CoreImage, UIKit; these are source dependencies, not architecture labels.

Project structure

Source bundle/
├── ConstantColorCam/
│   ├── ConstantColorCamApp.swift
│   ├── CameraView.swift
│   ├── PhotosTabView.swift
│   ├── ContentView.swift
│   ├── DataModel.swift
│   ├── ViewFinderView.swift
│   ├── Camera.swift
│   └── PhotoLibrary.swift
├── Configuration/
│   └── SampleCode.xcconfig
└── ConstantColorCam.xcodeproj/
    ├── .xcodesamplecode.plist
    └── project.pbxproj

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 3 project/configuration file(s) and 11 source declaration(s).

Overall architecture

Reference code

ConstantColorCam/ConstantColorCamApp.swift:10 — architecture anchor

@main
struct ConstantColorCamApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView().preferredColorScheme(.dark)
        }
    }
}

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 AVFoundation.

Ownership and state

Ownership evidence

ConstantColorCam/CameraView.swift:13 — stored dependency or nearest verified ownership anchor

struct CameraView: View {
    // ...
    @State private var model = DataModel()
    // ...
}
Owner Object or state Relationship Mutation authority
CameraView DataModel (model) owns wrapper-managed state Owning lexical scope
CameraView Showflasherror (showFlashError) stores or receives App/module collaborators
CameraView Showfallbackphotodeliveryerror (showFallbackPhotoDeliveryError) stores or receives App/module collaborators
ShutterButton Callback (action) stores a callback 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. ConstantColorCam/Camera.swift:158
Suspension boundary async declaration or closure The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. ConstantColorCam/Camera.swift:244
Task creation Task The source creates an unstructured task; surrounding context determines inherited actor isolation. ConstantColorCam/CameraView.swift:74
Main isolation @MainActor The cited annotation marks its attached declaration or closure as main-actor isolated. ConstantColorCam/DataModel.swift:26
Main isolation Task closure isolated to MainActor The cited operation explicitly enters a main-actor-isolated region. ConstantColorCam/DataModel.swift:26

@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

ConstantColorCam/Camera.swift:158 — representative execution boundary

class Camera: NSObject {
    // ...
        sessionQueue = DispatchQueue(label: "session queue")
    // ...
}

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. ConstantColorCam/CameraView.swift:13
State propagation @Observable Observation macro publishes source-visible changes. ConstantColorCam/DataModel.swift:10
Source import SwiftUI The cited file imports this module; runtime use and architectural role are not inferred. ConstantColorCam/Camera.swift:11
Source import Photos The cited file imports this module; runtime use and architectural role are not inferred. ConstantColorCam/Camera.swift:10
Source import os The cited file imports this module; runtime use and architectural role are not inferred. ConstantColorCam/Camera.swift:9
Source import CoreImage The cited file imports this module; runtime use and architectural role are not inferred. ConstantColorCam/Camera.swift:8
Source import UIKit The cited file imports this module; runtime use and architectural role are not inferred. ConstantColorCam/Camera.swift:12
Source import VideoToolbox The cited file imports this module; runtime use and architectural role are not inferred. ConstantColorCam/Camera.swift:13

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

ConstantColorCam/ConstantColorCamApp.swift:11 — representative type boundary

@main
struct ConstantColorCamApp: App {
    // ...
            ContentView().preferredColorScheme(.dark)
    // ...
}
Type Responsibility Depends on or conforms to
ConstantColorCamApp Application entry and top-level composition App
CameraView User-interface presentation and input forwarding View
PhotosTabView User-interface presentation and input forwarding View
ImageView User-interface presentation and input forwarding View
ContentView User-interface presentation and input forwarding View
DataModel Feature data or observable state Concrete collaborators/imported frameworks
ViewFinderView User-interface presentation and input forwarding View
ShutterButton Represents a feature value or composable behavior View
CameraOptionToggle Represents a feature value or composable behavior View
Camera Owns feature behavior and collaborator lifecycle NSObject

No local protocol conformance is claimed as protocol-oriented design; external framework conformances are listed only as dependencies.

Access control

Symbol Access Verified effect Likely rationale
captureSession (ConstantColorCam/Camera.swift:18) 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.
isCaptureSessionConfigured (ConstantColorCam/Camera.swift:21) 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.
deviceInput (ConstantColorCam/Camera.swift:24) 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.
photoOutput (ConstantColorCam/Camera.swift:27) 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.

Reference code

ConstantColorCam/Camera.swift:18 — representative boundary

class Camera: NSObject {
    // ...
    private let captureSession = AVCaptureSession()
    // ...
}

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 ConstantColorCamApp The source’s App suffix makes this role explicit.
Feature data or observable state DataModel The source’s Model suffix makes this role explicit.
User-interface presentation and input forwarding CameraView, ContentView, ImageView, PhotosTabView The source’s View suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks ConstantColorCam/Camera.swift:456 Callback protocols invert event delivery back into the sample’s owner.
Binding-based state propagation ConstantColorCam/CameraView.swift:159 A binding exposes controlled read/write access while the upstream owner remains authoritative.

Main application flow

Reference code

ConstantColorCam/Camera.swift:389takePhoto

    func takePhoto() {
        guard let photoOutput else { return }
        constantColorPhoto = nil
        fallbackFrame = nil
        confidenceMap = nil
        normalPhoto = nil
        let photoSettings = AVCapturePhotoSettings()
        photoOutputReadinessCoordinator.startTrackingCaptureRequest(using: photoSettings)
        sessionQueue.async {
            photoSettings.flashMode = self.flashEnabled ? .on : .off
           if self.constantColorSupported {
                photoSettings.isConstantColorEnabled = self.constantColorEnabled
                photoSettings.isConstantColorFallbackPhotoDeliveryEnabled = self.fallBackPhotoDeliveryEnabled
           }
            photoSettings.maxPhotoDimensions = photoOutput.maxPhotoDimensions
            if let previewPhotoPixelFormatType = photoSettings.availablePreviewPhotoPixelFormatTypes.first {
                photoSettings.previewPhotoFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPhotoPixelFormatType]
            }
            photoSettings.photoQualityPrioritization = .balanced
            photoOutput.connection(with: .video)?.videoRotationAngle = 90
            self.videoOutput?.connection(with: .video)?.videoRotationAngle = 90
            photoOutput.capturePhoto(with: photoSettings, delegate: self)
            self.photoOutputReadinessCoordinator.stopTrackingCaptureRequest(using: photoSettings.uniqueID)
        }
    }

Naming conventions

  • Types: App: ConstantColorCamApp; Model: DataModel; View: CameraView, ContentView, ImageView, PhotosTabView, ViewFinderView.
  • Protocols: no local protocol declaration in the scanned source.
  • Methods: takePhoto, handleCameraPreviews, initialize, configureCaptureSession, checkCameraAuthorization, checkPhotoAuthorization, deviceInputFor, createImageFromPixelBuffer.
  • Files: ConstantColorCam/ConstantColorCamApp.swift, ConstantColorCam/CameraView.swift, ConstantColorCam/PhotosTabView.swift, ConstantColorCam/ContentView.swift, ConstantColorCam/DataModel.swift, ConstantColorCam/ViewFinderView.swift.

Architecture takeaways

  • ConstantColorCamApp is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches SwiftUI, Photos, CoreImage, UIKit 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.
  • The source does not justify labeling the design protocol-oriented.

Source map

Source file Relevant symbols
ConstantColorCam/ConstantColorCamApp.swift Cited implementation, ConstantColorCamApp
ConstantColorCam/CameraView.swift Cited implementation, Task, SwiftUI state property wrapper, CameraView, ShutterButton, CameraOptionToggle
ConstantColorCam/Camera.swift Cited implementation, DispatchQueue(label:), async declaration or closure, SwiftUI, Photos, os, CoreImage, UIKit, VideoToolbox, Camera
ConstantColorCam/DataModel.swift @MainActor, Task closure isolated to MainActor, @Observable, DataModel
ConstantColorCam/PhotosTabView.swift PhotosTabView, ImageView
ConstantColorCam/ContentView.swift ContentView
ConstantColorCam/ViewFinderView.swift ViewFinderView
ConstantColorCam/PhotoLibrary.swift PhotoLibrary