Detect permission of camera in iOS
Check the AVAuthorizationStatus
and handle the cases properly.
NSString *mediaType = AVMediaTypeVideo;AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];if(authStatus == AVAuthorizationStatusAuthorized) { // do your logic} else if(authStatus == AVAuthorizationStatusDenied){ // denied} else if(authStatus == AVAuthorizationStatusRestricted){ // restricted, normally won't happen} else if(authStatus == AVAuthorizationStatusNotDetermined){ // not determined?! [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) { if(granted){ NSLog(@"Granted access to %@", mediaType); } else { NSLog(@"Not granted access to %@", mediaType); } }];} else { // impossible, unknown authorization status}
Swift 4 and newer
Make sure to:
import AVFoundation
The code below checks for all possible permission states:
let cameraMediaType = AVMediaType.videolet cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: cameraMediaType) switch cameraAuthorizationStatus {case .denied: breakcase .authorized: breakcase .restricted: breakcase .notDetermined: // Prompting user for the permission to use the camera. AVCaptureDevice.requestAccess(for: cameraMediaType) { granted in if granted { print("Granted access to \(cameraMediaType)") } else { print("Denied access to \(cameraMediaType)") } }}
Since iOS 10 you need to specifyNSCameraUsageDescription
key in your Info.plist to be able ask for camera access, otherwise your app will crash at runtime. See APIs Requiring Usage Descriptions.
An interesting sidenote from Apple Developer forum:
The system actually kills your app if the user toggles your app'saccess to camera in Settings. The same applies to any protecteddataclass in the Settings→Privacy section.
Swift Solution
extension AVCaptureDevice { enum AuthorizationStatus { case justDenied case alreadyDenied case restricted case justAuthorized case alreadyAuthorized case unknown } class func authorizeVideo(completion: ((AuthorizationStatus) -> Void)?) { AVCaptureDevice.authorize(mediaType: AVMediaType.video, completion: completion) } class func authorizeAudio(completion: ((AuthorizationStatus) -> Void)?) { AVCaptureDevice.authorize(mediaType: AVMediaType.audio, completion: completion) } private class func authorize(mediaType: AVMediaType, completion: ((AuthorizationStatus) -> Void)?) { let status = AVCaptureDevice.authorizationStatus(for: mediaType) switch status { case .authorized: completion?(.alreadyAuthorized) case .denied: completion?(.alreadyDenied) case .restricted: completion?(.restricted) case .notDetermined: AVCaptureDevice.requestAccess(for: mediaType, completionHandler: { (granted) in DispatchQueue.main.async { if granted { completion?(.justAuthorized) } else { completion?(.justDenied) } } }) @unknown default: completion?(.unknown) } }}
And then in order to use it you do
AVCaptureDevice.authorizeVideo(completion: { (status) in //Your work here})