How do I capture photos and video with AVFoundation in Swift?

AVFoundation is a powerful framework in Swift for capturing photos and videos using the device's camera. Below, you'll find an example of how to set up the camera, capture photos, and record videos.

import UIKit import AVFoundation class ViewController: UIViewController, AVCapturePhotoCaptureDelegate, AVCaptureFileOutputRecordingDelegate { var captureSession: AVCaptureSession! var photoOutput: AVCapturePhotoOutput! var videoOutput: AVCaptureMovieFileOutput! var previewLayer: AVCaptureVideoPreviewLayer! override func viewDidLoad() { super.viewDidLoad() setupCamera() } func setupCamera() { captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { return } photoOutput = AVCapturePhotoOutput() if (captureSession.canAddOutput(photoOutput)) { captureSession.addOutput(photoOutput) } videoOutput = AVCaptureMovieFileOutput() if (captureSession.canAddOutput(videoOutput)) { captureSession.addOutput(videoOutput) } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = view.layer.bounds previewLayer.videoGravity = .resizeAspectFill view.layer.addSublayer(previewLayer) captureSession.startRunning() } func capturePhoto() { let settings = AVCapturePhotoSettings() photoOutput.capturePhoto(with: settings, delegate: self) } func startRecording() { let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent("video.mp4") videoOutput.startRecording(to: outputURL, recordingDelegate: self) } func stopRecording() { videoOutput.stopRecording() } func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { guard let imageData = photo.fileDataRepresentation() else { return } let image = UIImage(data: imageData) // Use the image (e.g. save to photo library) } func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { // Handle the recorded video file (e.g., save to photo library) } }

AVFoundation Capture Photos Video Recording Swift Camera iOS Camera Framework