How to detect user has clicked Don't Allow acc

2020-04-07 05:23发布

问题:

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)

回答1:

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!



回答2:

In iOS 10, use:

import Photos

let authStatus = PHPhotoLibrary.authorizationStatus()
if authStatus == .notDetermined || authStatus == .denied {
    PHPhotoLibrary.requestAuthorization({ (status) in
        if status == PHAuthorizationStatus.authorized {

        } else {
            imagePickerController.dismissViewControllerAnimated(true, completion: nil)
        }
    })
}


回答3:

Check out this for detecting camera permission

Presenting camera permission dialog in iOS 8

Use this when user picks Don't Allow.

PhotoPicker.dismissViewControllerAnimated(false, completion: nil)