Swift Programming Guide: Capturing Image from Camera
Overview
This guide provides a step-by-step example of how to capture an image from the camera using Swift.
Requirements
Xcode 13 or later
iOS 15 or later
iPhone or iPad with a camera
Example Code
swift
import UIKit
import AVFoundation
class CameraViewController: UIViewController {
// 1. Create a AVCaptureSession to manage the camera
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
varstillImageOutput: AVCapturePhotoOutput?
override func viewDidLoad() {
super.viewDidLoad()
// 2. Initialize the capture session
captureSession = AVCaptureSession()
// 3. Create a AVCaptureDeviceInput to get the camera input
guard let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
return
}
let videoInput = try! AVCaptureDeviceInput(device: camera)
// 4. Add the video input to the capture session
captureSession.addInput(videoInput)
// 5. Create a AVCapturePhotoOutput to capture the image
stillImageOutput = AVCapturePhotoOutput()
captureSession.addOutput(stillImageOutput!)
// 6. Create a AVCaptureVideoPreviewLayer to display the camera preview
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)!
previewLayer.frame = view.bounds
view.layer.addSublayer(previewLayer)
// 7. Start the capture session
captureSession.startRunning()
}
// 8. Allow the user to capture an image
@objc func captureImage() {
let settings: AVCapturePhotoSettings = AVCapturePhotoSettings()
stillImageOutput?.capturePhoto(with: settings, delegate: self)
}
// 9. Handle the captured image
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let data = photo.fileDataRepresentation() else { return }
// Save the captured image to the photo library
let savedImage = UIImage(data: data)
UIImageWriteToSavedPhotosAlbum(savedImage!, self, #selector(image(_:didFinishSavingWithError:contextInfo:))
// Display the captured image
previewLayer.removeFromSuperview()
view.addSubview(UIImageView(image: savedImage!))
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print("Error saving image: \(error.localizedDescription)")
} else {
print("Image saved to photo library")
}
}
}
Explanation
This code uses the AVFoundation framework to capture an image from the camera. Here's a step-by-step breakdown:
Create a AVCaptureSession: This object manages the camera and its inputs and outputs.
Initialize the capture session: Create a new AVCaptureSession and add the camera input to it.
Create a AVCapturePhotoOutput: This object captures the image and stores it as a photo.
Create a AVCaptureVideoPreviewLayer: This layer displays the camera preview.
Start the capture session: Start the camera preview.
Allow the user to capture an image: Add a button to the view controller to capture an image.
Handle the captured image: When an image is captured, save it to the photo library and display it on the screen.
Example Use Case
To use this code, create a new Xcode project and replace the contents of the ViewController.swift file with the above code. Run the app on a physical device or simulator. Tap the Take Photo button to capture an image and save it to the photo library.
Make sure to add the necessary permissions to the Info.plist file to access the camera and photo library.
Permissions
NSPhotoLibraryUsageDescription for accessing the photo library
NSCameraUsageDescription for accessing the camera
Note
This is a basic example to get you started. You can customize the code to suit your needs, such as adding error handling, cropping the image, or applying filters.
The error message you're encountering is due to trying to force unwrap an optional value (try! AVCaptureDeviceInput(device: camera)) inside a conditional binding (guard let camera = ... else { return }).
Here's the corrected code:
swift
import UIKit
import AVFoundation
class CameraViewController: UIViewController {
// 1. Create a AVCaptureSession to manage the camera
var captureSession: AVCaptureSession?
var previewLayer: AVCaptureVideoPreviewLayer?
var stillImageOutput: AVCapturePhotoOutput?
override func viewDidLoad() {
super.viewDidLoad()
// 2. Initialize the capture session
captureSession = AVCaptureSession()
// 3. Create a AVCaptureDeviceInput to get the camera input
guard let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
return
}
do {
let videoInput = try AVCaptureDeviceInput(device: camera)
// 4. Add the video input to the capture session
if let captureSession = captureSession {
captureSession.addInput(videoInput)
}
} catch {
print("Error creating AVCaptureDeviceInput: \(error.localizedDescription)")
return
}
// 5. Create a AVCapturePhotoOutput to capture the image
stillImageOutput = AVCapturePhotoOutput()
if let captureSession = captureSession {
captureSession.addOutput(stillImageOutput!)
}
// 6. Create a AVCaptureVideoPreviewLayer to display the camera preview
if let captureSession = captureSession {
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)!
previewLayer.frame = view.bounds
view.layer.addSublayer(previewLayer)
}
// 7. Start the capture session
if let captureSession = captureSession {
captureSession.startRunning()
}
}
// 8. Allow the user to capture an image
@objc func captureImage() {
let settings: AVCapturePhotoSettings = AVCapturePhotoSettings()
stillImageOutput?.capturePhoto(with: settings, delegate: self)
}
// 9. Handle the captured image
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let data = photo.fileDataRepresentation() else { return }
// Save the captured image to the photo library
let savedImage = UIImage(data: data)
UIImageWriteToSavedPhotosAlbum(savedImage!, self, #selector(image(_:didFinishSavingWithError:contextInfo:))
// Display the captured image
previewLayer?.removeFromSuperlayer()
let imageView = UIImageView(image: savedImage!)
view.addSubview(imageView)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print("Error saving image: \(error.localizedDescription)")
} else {
print("Image saved to photo library")
}
}
}
In the corrected code:
captureSession is declared as an optional (var captureSession: AVCaptureSession?) to match the return type of AVCaptureSession().
The do-try-catch block is used to handle errors when creating the AVCaptureDeviceInput.
The if let statements are used to unwrap the captureSession and its properties only if they are not nil.