Swift Cheat Sheet for iPhone Camera Access & Usage

This is a cheat sheet of the code and workflow for iPhone camera access and usage, from requesting permission to using the photo taken with a user’s device.

Framework Import

import AVFoundation

Set Camera Usage Description in Info.plist

When you request permission to use the device’s camera, a short message will appear in the default iOS system dialog. You customize this message by adding the Privacy - Camera Usage Description key to your Info.plist file.

For the value of this plist property, type a short string describing what you’re using the camera for.

If you don’t set this, your app will crash when you request access to the camera.

Check and Respond to Camera Authorization Status

1let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
2
3switch cameraAuthorizationStatus {
4case .notDetermined: requestCameraPermission()
5case .authorized: presentCamera()
6case .restricted, .denied: alertCameraAccessNeeded()
7}

Request Camera Permission

If the user has never responded to a request to access his/her camera, you need to prompt with the iOS system alert to request permission:

1func requestCameraPermission() {
2    AVCaptureDevice.requestAccess(for: .video, completionHandler: {accessGranted in
3        guard accessGranted == true else { return }
4        self.presentCamera()
5    })
6}

Note: You can test for this case by deleting the app on the device, if it’s already been installed or run on a device from the debugger.

Present Camera

1func presentCamera() {
2    let photoPicker = UIImagePickerController()
3    photoPicker.sourceType = .camera
4    photoPicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
5    
6    self.present(photoPicker, animated: true, completion: nil)
7}

Alert Camera Access Needed

If camera access has been denied or restricted, you can alert the user and direct them to the Settings app to make the appropriate permissions adjustment:

 1func alertCameraAccessNeeded() {
 2    let settingsAppURL = URL(string: UIApplicationOpenSettingsURLString)!
 3    
 4    let alert = UIAlertController(
 5        title: "Need Camera Access",
 6        message: "Camera access is required to make full use of this app.",
 7        preferredStyle: UIAlertControllerStyle.alert
 8    )
 9
10    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
11    alert.addAction(UIAlertAction(title: "Allow Camera", style: .cancel, handler: { (alert) -> Void in
12        UIApplication.shared.open(settingsAppURL, options: [:], completionHandler: nil)
13    }))
14
15    present(alert, animated: true, completion: nil)
16}

Note: You can test for this case by going to the Settings app and turning off camera access for your app, if it’s been previously granted.

Use the Captured Image

To use the image that the camera captured, you need to set up your view controller to adhere to and implement couple of delegate protocols:

1class NameOfViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
2// ...
3}

UIImagePickerControllerDelegate

1func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
2    let photo = info[UIImagePickerControllerOriginalImage] as! UIImage
3    // do something with the photo... set to UIImageView, save it, etc.
4
5    dismiss(animated: true, completion: nil)
6}

comments powered by Disqus