Search code examples
iospermissionscamerauiimagepickercontrollerios-permissions

Detect permission of camera in iOS


I am developing a very simple video app. I use the official control: UIImagePickerController.

Here is the problem. When presenting the UIImagePickerController for the first time, the iOS will ask for the permission. The user can click yes or no. If the user clicks no, the control is not dismissed. Instead, if the user keeps clicking the start button, the timers go on while the screen is always black, and the user can't stop the timers or go back. The only thing the user can do is to kill the app. The next time the UIImagePickerController is presented, it is still a black screen and the user can't go back if clicking start.

I was wondering if it's a bug. Is there any way we can detect the permission of the camera so that we can decide to show the UIImagePickerController or not?


Solution

  • 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
    }