Instantly share code, notes, and snippets.
Created
May 7, 2022 20:54
Request Camera Authorization - Snippet 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import AVFoundation | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let authorizationStatus = getCameraAuthorization() | |
switch authorizationStatus { | |
case .notDetermined: | |
print("Camera permission has not yet granted. We can request camera permission from the user") | |
// 2: Call the Request Camera Authorization method | |
requestCameraAuthorization { granted in | |
// 3: Print the status | |
let grantedStatus = granted ? "granted" : "not granted" | |
print("Camera permission was \(grantedStatus)") | |
} | |
case .restricted: | |
print("User is not allowed to access media capture device.") | |
case .denied: | |
print("User has denied accessing camera. We need to request user to allow the camera permission from settings.") | |
case .authorized: | |
print("Camera permission was granted") | |
@unknown default: | |
print("Camera authorization status is unknown.") | |
} | |
} | |
func getCameraAuthorization() -> AVAuthorizationStatus { | |
let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video) | |
return authorizationStatus | |
} | |
// 1: Create method to Request Camera Authorization | |
func requestCameraAuthorization(completionHandler: @escaping (Bool) -> Void) { | |
AVCaptureDevice.requestAccess(for: .video) { granted in | |
completionHandler(granted) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment