5

When the app tries to access the Camera API's in iOS than an OS level alertview is shown. The user here has to allow access to camera or disable the access.

My question is how can I get notified of the selection made by the user..?

Say he selected don't allow access than is there any notification raised which I can use in my app..?

Any help is appreciated.

Ankit Srivastava
  • 12,347
  • 11
  • 63
  • 115

2 Answers2

25

Instead of letting the OS show the alert view when the camera appears, you can check for the current authorization status, and request for the authorization manually. That way, you get a callback when the user accepts/rejects your request.

In swift:

let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
if status == AVAuthorizationStatus.Authorized {
    // Show camera
} else if status == AVAuthorizationStatus.NotDetermined {
    // Request permission
    AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) -> Void in
        if granted {
            // Show camera
        }
    })
} else {
    // User rejected permission. Ask user to switch it on in the Settings app manually
}

If the user has previously rejected the request, calling requestAccessForMediaType will not show the alert and will execute the completion block immediately. In this case, you can choose to show your custom alert and link the user to the settings page. More info on this here.

Community
  • 1
  • 1
ken
  • 3,897
  • 3
  • 22
  • 28
0

Taken from Kens answer, I've created this Swift 3 protocol to handle permission access:

import AVFoundation

protocol PermissionHandler {
    func handleCameraPermissions(completion: @escaping ((_ error: Error?) -> Void))
}

extension PermissionHandler {

    func handleCameraPermissions(completion: @escaping ((_ error: Error?) -> Void)) {
        let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)

        switch status {
        case .authorized:
            completion(nil)
        case .restricted:
            completion(ClientError.noAccess)
        case .notDetermined:
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
                if granted {
                    completion(nil)
                } else {
                    completion(ClientError.noAccess)
                }
            }
        case .denied:
            completion(ClientError.noAccess)
        }
    }
}

You can then conform to this protocol and call it in your class like so:

handleCameraPermissions() { error in
    if let error = error {
        //Denied, handle error here
        return
    }

    //Allowed! As you were
Harry Bloom
  • 2,359
  • 25
  • 17