Search code examples
iosswiftxcode6uiimagepickercontroller

How to detect user has clicked Don't Allow access to camera


I am using a UIImagePicker to present the users with camera to take photos which will be used in the app.

My problem is that on the first time a user opens the image picker they are presented with a prompt saying: '"my App" Would like to Access your Camera' with two options, Don't allow and OK.

My requirement is that when the user clicks Don't Allow, the Image picker gets dismissed leaving a black view. Is there a way to detect that the user has chosen Don't allow?

Here is my code to present UIImagePicker:

var PhotoPicker:UIImagePickerController = UIImagePickerController()
PhotoPicker.delegate = self
PhotoPicker.sourceType = .Camera
PhotoPicker.cameraFlashMode = .Off
PhotoPicker.showsCameraControls = false
PhotoPicker.cameraDevice = .Rear
self.presentViewController(PhotoPicker, animated: false, completion: nil)

Solution

  • To detect access to your library:

    You need to use AssetsLibrary for that. First, import assets library framework:

    import AssetsLibrary
    

    Then, request authorization status, and if it is not determined, use blocks to catch those events, like this:

    if ALAssetsLibrary.authorizationStatus() == ALAuthorizationStatus.NotDetermined {
    
        let library = ALAssetsLibrary()
        library.enumerateGroupsWithTypes(.All, usingBlock: { (group, stop) -> Void in
    
            // User clicked ok
        }, failureBlock: { (error) -> Void in
    
            // User clicked don't allow
            imagePickerController.dismissViewControllerAnimated(true, completion: nil)
        })
    }
    

    To detect access to camera:

    You need to use AVFoundation for that. First, import avfoundation framework:

    import AVFoundation
    

    Then, as previously, request user permission when you go to imagepicker and catch the event.

    if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == AVAuthorizationStatus.NotDetermined {
    
        AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (videoGranted: Bool) -> Void in
    
            // User clicked ok
            if (videoGranted) {
    
            // User clicked don't allow
            } else {
                imagePickerController.dismissViewControllerAnimated(true, completion: nil)
            }
        })
    }
    

    Hope it helps!