SwiftUI camera capture with AVFoundation: a session actor, a preview layer and photo capture
Build photo capture in SwiftUI with AVFoundation: permissions, a session actor, a preview layer, async capture, rotation and interruptions.
· 9 min read
- AVFoundation
- Camera
- SwiftUI
SwiftUI has no camera view. To show a live preview and take a photo you still use AVFoundation, which predates Swift concurrency and SwiftUI by many years. The result is that most camera code in the wild has the same handful of faults: startRunning() called on the main thread, a photo delegate that is never turned into something awaitable, photos that come out sideways, and no plan for when the system takes the camera away.
This article builds a small photo-capture feature that avoids those, following the structure of Apple’s AVCam sample. We checked the API names, signatures and availability against Apple’s documentation, but we could not compile or run the code, so details such as concurrency annotations may need adjusting. Build it in Xcode and test it on a real device, because the Simulator has no camera. It assumes iOS 17 or later, where AVCaptureDevice.RotationCoordinator arrived, and Swift 5.10 or later for nonisolated(unsafe).
Set the privacy key first
Add NSCameraUsageDescription to your Info.plist with a sentence explaining why you need the camera. Apple’s documentation is blunt about this: the key has to be present before you request authorisation or use a capture device, otherwise the system terminates your app.
One actor owns the session
Apple’s documentation describes AVCaptureSession.startRunning() as a blocking call that can take some time, and AVCam keeps capture calls off the main thread by putting them in an actor. Configuring the session is similar. So all session work lives in one actor that isn’t the main actor, as in AVCam:
import AVFoundation
enum CameraError: Error {
case notAuthorized, noCamera, cannotAddInput, cannotAddOutput, noPhotoData
}
actor CameraService {
// AVCaptureSession isn't Sendable. The preview layer only reads it;
// every change to it happens inside this actor.
nonisolated(unsafe) let session = AVCaptureSession()
private let photoOutput = AVCapturePhotoOutput()
private var rotationCoordinator: AVCaptureDevice.RotationCoordinator?
private var isConfigured = false
private var inFlight: [Int64: PhotoDelegate] = [:]
private var isAuthorized: Bool {
get async {
let status = AVCaptureDevice.authorizationStatus(for: .video)
if status == .notDetermined {
return await AVCaptureDevice.requestAccess(for: .video)
}
return status == .authorized
}
}
nonisolated static func backCamera() -> AVCaptureDevice? {
AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
}
func start() async throws {
guard await isAuthorized else { throw CameraError.notAuthorized }
try Task.checkCancellation() // the screen may have gone while the prompt was up
if !isConfigured { try configure() }
if !session.isRunning { session.startRunning() }
}
func stop() {
if session.isRunning { session.stopRunning() }
}
}
The authorisation check is Apple’s own pattern: read authorizationStatus(for:) first, and only call requestAccess(for:) when the status is .notDetermined. The system remembers the answer, so the prompt appears once. Call start() when the user opens the camera screen, not at launch, so the prompt arrives when its purpose is obvious.
Note the await inside start(). An actor is reentrant at suspension points, so a second call to start() can begin while the first waits for the permission prompt. The isConfigured flag makes that harmless, and Task.checkCancellation() stops a screen that has already disappeared from starting the camera once the user answers.
nonisolated(unsafe) is a deliberate shortcut, because AVCaptureSession isn’t Sendable. AVCam passes the session to its preview view through a small protocol instead, which you may prefer. Either way: one owner, and no session calls from anywhere else.
Configure the session in one transaction
extension CameraService {
private func configure() throws {
guard let camera = Self.backCamera() else { throw CameraError.noCamera }
let input = try AVCaptureDeviceInput(device: camera)
guard session.canAddInput(input) else { throw CameraError.cannotAddInput }
guard session.canAddOutput(photoOutput) else { throw CameraError.cannotAddOutput }
session.beginConfiguration()
session.sessionPreset = .photo
session.addInput(input)
session.addOutput(photoOutput)
session.commitConfiguration()
// Allow the largest photos the active format supports. We read the format after
// the commit in case the preset changes it; check that on a device.
if let largest = camera.activeFormat.supportedMaxPhotoDimensions
.max(by: { $0.width * $0.height < $1.width * $1.height }) {
photoOutput.maxPhotoDimensions = largest
}
rotationCoordinator = AVCaptureDevice.RotationCoordinator(
device: camera, previewLayer: nil
)
isConfigured = true
}
}
Three points come from Apple’s documentation:
beginConfiguration()andcommitConfiguration()make a set of changes one atomic update. We run bothcanAddchecks before changing anything, so a failure leaves the session untouched.- The
.photopreset optimises the pipeline for high-quality stills. maxPhotoDimensionsmust be one of the values in the active format’ssupportedMaxPhotoDimensions, and should be set beforestartRunning(), because changing it can cause a lengthy reconfiguration. It is a ceiling. Because we also set it on each photo’s settings, photos come out at the largest size the device offers, which can be very large; leave that line out if you don’t need it. Options such as Live Photo capture reconfigure the pipeline too, so enable them up front, not when the user taps the shutter.
The preview layer
The live preview is an AVCaptureVideoPreviewLayer, a Core Animation layer. SwiftUI can’t host a layer directly, so wrap a UIView whose backing layer is the preview layer. This is the same approach AVCam takes:
import SwiftUI
import AVFoundation
struct CameraPreview: UIViewRepresentable {
let session: AVCaptureSession
let isRunning: Bool
func makeUIView(context: Context) -> PreviewView {
let view = PreviewView()
view.previewLayer.session = session
view.previewLayer.videoGravity = .resizeAspectFill
return view
}
func updateUIView(_ uiView: PreviewView, context: Context) {
// Once the session runs, the layer has a connection to rotate.
if isRunning, let camera = CameraService.backCamera() {
uiView.trackRotation(of: camera)
}
}
}
PreviewView is shown in the rotation section below. Connecting the layer to the session doesn’t start anything. The preview shows frames only once the actor has called startRunning().
Take a photo as an async call
AVCapturePhotoOutput.capturePhoto(with:delegate:) is the only call for stills. It has two rules that matter:
- Every capture needs a new
AVCapturePhotoSettings. Apple’s documentation says reusing one throws anNSInvalidArgumentException. The method copies the settings you pass. - The delegate is told about progress and results through callbacks. For a plain still,
photoOutput(_:didFinishProcessingPhoto:error:)delivers the photo andphotoOutput(_:didFinishCaptureFor:error:)is called once at the end. Apple’s guide suggests one delegate instance per capture, so overlapping captures don’t tangle.
A checked continuation bridges that to async, as AVCam does. Collect the data in the first callback and resume in the last:
private final class PhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate, @unchecked Sendable {
private let continuation: CheckedContinuation<Data, Error>
private var data: Data?
private var processingError: Error?
init(_ continuation: CheckedContinuation<Data, Error>) {
self.continuation = continuation
}
func photoOutput(_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photo: AVCapturePhoto,
error: Error?) {
processingError = error
data = photo.fileDataRepresentation()
}
func photoOutput(_ output: AVCapturePhotoOutput,
didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings,
error: Error?) {
if let error = error ?? processingError {
continuation.resume(throwing: error)
} else if let data {
continuation.resume(returning: data)
} else {
continuation.resume(throwing: CameraError.noPhotoData)
}
}
}
fileDataRepresentation() returns Data? in the format you asked for, and nil if the photo can’t be flattened, hence the final branch. Apple says didFinishCaptureFor is called exactly once per request, which makes it a safe place to resume the continuation. The class is @unchecked Sendable on the assumption, not documented by Apple, that its two properties are touched only by one capture’s callbacks, one after another. The actor’s inFlight dictionary keeps each delegate alive until its capture ends, as Apple’s photo-progress article does for overlapping captures.
The capture method on the actor builds fresh settings, applies the rotation (next section) and awaits the delegate:
extension CameraService {
func capturePhoto() async throws -> Data {
let settings = photoOutput.availablePhotoCodecTypes.contains(.hevc)
? AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.hevc])
: AVCapturePhotoSettings()
settings.maxPhotoDimensions = photoOutput.maxPhotoDimensions
if let angle = rotationCoordinator?.videoRotationAngleForHorizonLevelCapture,
let connection = photoOutput.connection(with: .video),
connection.isVideoRotationAngleSupported(angle) {
connection.videoRotationAngle = angle
}
// The delegate stays in `inFlight` until the capture finishes.
defer { inFlight[settings.uniqueID] = nil }
return try await withCheckedThrowingContinuation { continuation in
let delegate = PhotoDelegate(continuation)
inFlight[settings.uniqueID] = delegate
photoOutput.capturePhoto(with: settings, delegate: delegate)
}
}
}
HEVC, with a fall-back to JPEG on devices that lack it, is the choice Apple’s capture guide shows. In the view model, let data = try await camera.capturePhoto() is then ordinary code with ordinary error handling.
Rotation: use the coordinator
Photos that come out sideways are the classic camera bug, and since iOS 17 the fix is AVCaptureDevice.RotationCoordinator. It watches the device’s physical orientation and gives you angles that keep captured media level relative to gravity.
For the photo, read videoRotationAngleForHorizonLevelCapture and set it on the output’s connection, as above. Check isVideoRotationAngleSupported(_:) first, since only 0, 90, 180 and 270 are valid and anything else raises an exception. For a photo output the angle is recorded in the file’s Exif data, not applied by rotating pixels.
The preview has its own angle. Make a second coordinator that is given the preview layer, and apply videoRotationAngleForHorizonLevelPreview to the layer’s connection. The preview angle supports key-value observation, and Apple says its callbacks arrive on the main queue. Here is the complete preview view:
final class PreviewView: UIView {
override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }
var previewLayer: AVCaptureVideoPreviewLayer { layer as! AVCaptureVideoPreviewLayer }
private var rotationCoordinator: AVCaptureDevice.RotationCoordinator?
private var angleObservation: NSKeyValueObservation?
/// Call once the session is running, so the layer has a connection.
func trackRotation(of camera: AVCaptureDevice) {
guard rotationCoordinator?.device?.uniqueID != camera.uniqueID else { return } // already tracking
let coordinator = AVCaptureDevice.RotationCoordinator(
device: camera, previewLayer: previewLayer
)
angleObservation = coordinator.observe(
\.videoRotationAngleForHorizonLevelPreview, options: [.initial, .new]
) { [weak self] _, change in
// Apple says this callback arrives on the main queue; assumeIsolated
// would trap if it ever did not.
guard let self, let angle = change.newValue else { return }
MainActor.assumeIsolated {
self.previewLayer.connection?.videoRotationAngle = angle
}
}
rotationCoordinator = coordinator // keep both while the preview is on screen
}
}
.initial delivers the current angle straight away. Both the actor and the view get the camera from the same backCamera() helper, so they can’t disagree. If you let people switch cameras, call trackRotation(of:) with the new device; the guard lets it through because the device differs.
When the system takes the camera away
A camera session can be interrupted: another client takes the camera, an iPad app goes into Split View, Slide Over or Picture in Picture, or the system is under thermal pressure. AVCaptureSession posts wasInterruptedNotification when this happens and interruptionEndedNotification when it ends. The reason is in the notification’s userInfo under AVCaptureSessionInterruptionReasonKey:
// In whatever owns the session. Keep the returned token while you want callbacks.
let token = NotificationCenter.default.addObserver(
forName: AVCaptureSession.wasInterruptedNotification,
object: session, queue: .main
) { note in
guard let value = note.userInfo?[AVCaptureSessionInterruptionReasonKey] as? Int,
let reason = AVCaptureSession.InterruptionReason(rawValue: value) else { return }
// .videoDeviceNotAvailableWithMultipleForegroundApps, .videoDeviceInUseByAnotherClient,
// .videoDeviceNotAvailableDueToSystemPressure, ...
}
Use it to tell the user why the preview froze (“the camera isn’t available in Split View”), and clear the message when the interruption ends. Observe interruptionEndedNotification and runtimeErrorNotification the same way, because a camera that silently stops is a bad experience.
Wiring it into SwiftUI
Start the session when the screen appears and stop it when it goes away, so the camera isn’t held, and the battery drained, while the user is elsewhere:
struct CameraScreen: View {
let camera: CameraService
@State private var isRunning = false
@State private var errorMessage: String?
var body: some View {
CameraPreview(session: camera.session, isRunning: isRunning)
.ignoresSafeArea()
.overlay { if let errorMessage { Text(errorMessage) } }
.task {
do {
errorMessage = nil
try await camera.start()
isRunning = !Task.isCancelled
} catch CameraError.notAuthorized {
errorMessage = "Camera access is off. You can turn it on in Settings."
} catch is CancellationError {
// The screen went away while we were waiting.
} catch {
errorMessage = "The camera isn't available."
}
}
.onDisappear {
isRunning = false
Task { await camera.stop() }
}
}
}
After a refusal the system remembers the answer and won’t show the prompt again, so give the .notAuthorized message a button that opens the app’s page in Settings. As with purchases in StoreKit 2, derive what you can do from the system’s current state instead of assuming the happy path.
Testing
- Use a real device. The Simulator has no camera, so none of this runs there.
- Test the denied state, not only the granted one: switch camera access off for the app in Settings.
- Rotate the phone in all four orientations and with the rotation lock on, and check both the preview and the saved photo.
- Open the app in Split View or Slide Over on an iPad, and open another app that uses the camera, such as a video call, to see your interruption handling.
Camera features look small and hide a lot of platform behaviour. We build native apps with camera and AR features; see our iOS app development service.