我使用以下代码检查并请求相机的授权。问题如下。以下情况会导致错误的授权状态:
- 用户首次拒绝授权
- 终止应用程序
- 重新启动应用程序
- 离开应用程序,在设置应用程序中授予相机授权
- 返回应用程序
[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]
将返回AVAuthorizationStatusDeclined
(如上所述授权)。
在终止和重新启动后,会产生AVAuthorizationStatusAuthorized
。在这种情况下,用户继续设置并拒绝相机访问,结果将保持为AVAuthorizationStatusAuthorized
,直到下一次重新启动。
你知道我错过了什么吗?
- (void) popCamera {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
//picker.allowsEditing = YES;
#if !(TARGET_IPHONE_SIMULATOR)
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
#endif
self.view.translatesAutoresizingMaskIntoConstraints = YES;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)camDenied
{
NSLog(@"%@", @"Denied camera access");
NSString *alertText;
NSString *alertButton;
BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
if (canOpenSettings)
{
alertText = LSS(@"DeniedCamera1");
SDCAlertView *alert = [[SDCAlertView alloc]
initWithTitle:LSS(@"DeniedCameraTitle")
message:alertText
delegate:self
cancelButtonTitle:LSS(@"Cancel")
otherButtonTitles:LSS(@"Goto"), nil];
alert.tag = 3491832;
[alert show];
}
else
{
alertText = LSS(@"DeniedCamera2");
SDCAlertView *alert = [[SDCAlertView alloc]
initWithTitle:LSS(@"DeniedCameraTitle")
message:alertText
delegate:self
cancelButtonTitle:LSS(@"Cancel")
otherButtonTitles:nil];
alert.tag = 3491832;
[alert show];
}
}
- (IBAction) onTakePhoto:(id)sender {
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if(authStatus == AVAuthorizationStatusAuthorized)
{
[self popCamera];
}
else if(authStatus == AVAuthorizationStatusNotDetermined)
{
NSLog(@"%@", @"Camera access not determined. Ask for permission.");
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted)
{
if(granted)
{
[self popCamera];
}
else
{
[self camDenied];
}
}];
}
else if (authStatus == AVAuthorizationStatusRestricted)
{
SDCAlertView *alert = [[SDCAlertView alloc]
initWithTitle:LSS(@"RestrictCameraTitle")
message:LSS(@"RestrictCamera")
delegate:self
cancelButtonTitle:LSS(@"OK")
otherButtonTitles:nil];
}
else
{
[self camDenied];
}
}
原始代码的来源:在iOS 8上拒绝用户访问相机后,有没有办法要求用户访问相机?
这似乎是预期的行为。如果苹果希望你在运行时对授权更改做出反应,会有一个通知告诉你它已经更改。
但目前还没有这样的通知(据我所见)。您只需调用+authorizationStatusForMediaType:
,它就会返回最终状态(如拒绝或授权),或者返回AVAuthorizationStatusNotDetermined
,告诉您需要通过requestAccessForMediaType:completionHandler:
请求授权。
不幸的是,这不是一个权威的答案;我只是在这里得出结论和猜测。你可能想在苹果的开发者论坛上提问,并希望从苹果工程师那里得到答案。