有没有办法在用户已经在 iOS 上拒绝它之后要求用户访问相机?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26070393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to ask user for Camera access after they have already denied it on iOS?
提问by Ethan Allen
I am using this code, but unfortunately it doesn't work.
我正在使用此代码,但不幸的是它不起作用。
After a user has denied camera access, I want to ask them for permission to use the camera again the next time they try to load it (in this case it's a barcode scanner using the camera view). I always get AVAuthorizationStatusDenied
and then granted
always automatically returns NO
even though I ask for it again in code.
在用户拒绝相机访问后,我想请他们在下次尝试加载相机时再次使用相机(在这种情况下,它是使用相机视图的条形码扫描仪)。我总是得到AVAuthorizationStatusDenied
然后granted
总是自动返回,NO
即使我在代码中再次要求它。
Many of my users are e-mailing me saying "my screen is black when I try to barcode scan" and it's because they have denied camera access for some reason. I want to be able to prompt them again because most likely the denial was a mistake.
我的许多用户给我发电子邮件说“当我尝试条形码扫描时,我的屏幕是黑色的”,这是因为他们出于某种原因拒绝了相机访问。我希望能够再次提示他们,因为很可能拒绝是一个错误。
Is there a possible way to do this?
有没有可能的方法来做到这一点?
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if(authStatus == AVAuthorizationStatusAuthorized)
{
NSLog(@"%@", @"You have camera access");
}
else if(authStatus == AVAuthorizationStatusDenied)
{
NSLog(@"%@", @"Denied camera access");
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if(granted){
NSLog(@"Granted access to %@", AVMediaTypeVideo);
} else {
NSLog(@"Not granted access to %@", AVMediaTypeVideo);
}
}];
}
else if(authStatus == AVAuthorizationStatusRestricted)
{
NSLog(@"%@", @"Restricted, normally won't happen");
}
else if(authStatus == AVAuthorizationStatusNotDetermined)
{
NSLog(@"%@", @"Camera access not determined. Ask for permission.");
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if(granted){
NSLog(@"Granted access to %@", AVMediaTypeVideo);
} else {
NSLog(@"Not granted access to %@", AVMediaTypeVideo);
}
}];
}
else
{
NSLog(@"%@", @"Camera access unknown error.");
}
回答by Ethan Allen
After some research it looks like you can't do what I'd like. Here is the alternative that I coded to pop a dialog and open the Settings app automatically if on iOS 8+.
经过一番研究,看起来你不能做我想做的事。如果在 iOS 8+ 上,这是我编写的用于弹出对话框并自动打开“设置”应用程序的替代方法。
Some notes:
一些注意事项:
- Since iOS 10 you need to specify
NSCameraUsageDescription
key in your Info.plist to be able ask for camera access, otherwise your app will crash at runtime. - Once the user changes any permissions for your app, it will kill your app. Handle accordingly and save any needed data before the user hits that "Go" button.
- At some point between iOS 8 and 11, Apple no longer required the user to touch the Privacy cell in the Setting apps in order to get to and change the Camera settings. You may want to change your instructions on what the user is supposed to do in the Settings app based on what iOS version they are using. If someone wants to leave a comment below telling us all what exact iOS version that changed in, that would be awesome.
- 从 iOS 10 开始,您需要
NSCameraUsageDescription
在 Info.plist 中指定key 才能请求相机访问,否则您的应用程序将在运行时崩溃。 - 一旦用户更改了您的应用程序的任何权限,它就会杀死您的应用程序。在用户点击“开始”按钮之前,相应地处理并保存任何需要的数据。
- 在 iOS 8 和 11 之间的某个时间点,Apple 不再要求用户触摸设置应用程序中的隐私单元来访问和更改相机设置。您可能希望根据用户使用的 iOS 版本更改有关用户应该在“设置”应用程序中执行的操作的说明。如果有人想在下面发表评论告诉我们所有更改的确切 iOS 版本,那就太棒了。
Swift 4:
斯威夫特 4:
At the top of your view controller:
在视图控制器的顶部:
import AVFoundation
Before opening the camera view:
在打开相机视图之前:
@IBAction func goToCamera()
{
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch (status)
{
case .authorized:
self.popCamera()
case .notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
if (granted)
{
self.popCamera()
}
else
{
self.camDenied()
}
}
case .denied:
self.camDenied()
case .restricted:
let alert = UIAlertController(title: "Restricted",
message: "You've been restricted from using the camera on this device. Without camera access this feature won't work. Please contact the device owner so they can give you access.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
Denial alert with completion block:
带有完成块的拒绝警报:
func camDenied()
{
DispatchQueue.main.async
{
var alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Close this app.\n\n2. Open the Settings app.\n\n3. Scroll to the bottom and select this app in the list.\n\n4. Turn the Camera on.\n\n5. Open this app and try again."
var alertButton = "OK"
var goAction = UIAlertAction(title: alertButton, style: .default, handler: nil)
if UIApplication.shared.canOpenURL(URL(string: UIApplicationOpenSettingsURLString)!)
{
alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Touch the Go button below to open the Settings app.\n\n2. Turn the Camera on.\n\n3. Open this app and try again."
alertButton = "Go"
goAction = UIAlertAction(title: alertButton, style: .default, handler: {(alert: UIAlertAction!) -> Void in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
})
}
let alert = UIAlertController(title: "Error", message: alertText, preferredStyle: .alert)
alert.addAction(goAction)
self.present(alert, animated: true, completion: nil)
}
}
Objective-C:
目标-C:
At the top of your view controller:
在视图控制器的顶部:
#import <AVFoundation/AVFoundation.h>
Before opening the camera view:
在打开相机视图之前:
- (IBAction)goToCamera
{
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)
{
NSLog(@"Granted access to %@", AVMediaTypeVideo);
[self popCamera];
}
else
{
NSLog(@"Not granted access to %@", AVMediaTypeVideo);
[self camDenied];
}
}];
}
else if (authStatus == AVAuthorizationStatusRestricted)
{
// My own Helper class is used here to pop a dialog in one simple line.
[Helper popAlertMessageWithTitle:@"Error" alertText:@"You've been restricted from using the camera on this device. Without camera access this feature won't work. Please contact the device owner so they can give you access."];
}
else
{
[self camDenied];
}
}
Denial alert:
拒绝警告:
- (void)camDenied
{
NSLog(@"%@", @"Denied camera access");
NSString *alertText;
NSString *alertButton;
BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
if (canOpenSettings)
{
alertText = @"It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Touch the Go button below to open the Settings app.\n\n2. Turn the Camera on.\n\n3. Open this app and try again.";
alertButton = @"Go";
}
else
{
alertText = @"It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Close this app.\n\n2. Open the Settings app.\n\n3. Scroll to the bottom and select this app in the list.\n\n4. Turn the Camera on.\n\n5. Open this app and try again.";
alertButton = @"OK";
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Error"
message:alertText
delegate:self
cancelButtonTitle:alertButton
otherButtonTitles:nil];
alert.tag = 3491832;
[alert show];
}
Delegate call for the UIAlertView:
UIAlertView 的委托调用:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 3491832)
{
BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
if (canOpenSettings)
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
}
回答by StilesCrisis
Once they have denied camera access, the user can authorize camera use for your app in Settings. By design, you can't override this in your own code.
一旦他们拒绝了相机访问,用户就可以在“设置”中为您的应用授权使用相机。根据设计,您不能在自己的代码中覆盖它。
You can detect this case with the following sample code and then explain to the user how to fix it: iOS 7 UIImagePickerController Camera No Image
您可以使用以下示例代码检测这种情况,然后向用户解释如何修复它:iOS 7 UIImagePickerController Camera No Image
NSString *mediaType = AVMediaTypeVideo; // Or AVMediaTypeAudio
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
// The user has explicitly denied permission for media capture.
else if(authStatus == AVAuthorizationStatusDenied){
NSLog(@"Denied");
}
回答by ak_ninan
For Swift 3.0
对于 Swift 3.0
This will lead the user to settings for changing the permission.
这将引导用户进行更改权限的设置。
func checkCameraAuthorise() -> Bool {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == .restricted || status == .denied {
let dialog = ZAlertView(title: "", message: "Please allow access to the camera in the device's Settings -> Privacy -> Camera", isOkButtonLeft: false, okButtonText: "OK", cancelButtonText: "Cancel", okButtonHandler:
{ _ -> Void in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)}, cancelButtonHandler: { alertView in alertView.dismissAlertView() })
dialog.show()
return false
}
return true
}
回答by Alok
Full code of Camera access and photo library access
相机访问和照片库访问的完整代码
import AVFoundation
To handle camera action use the below code: Method calling
要处理相机动作,请使用以下代码:方法调用
func openCameraOrLibrary(){
let imagePicker = UIImagePickerController()
let alertController : UIAlertController = UIAlertController(title: "Select Camera or Photo Library".localized, message: "", preferredStyle: .actionSheet)
let cameraAction : UIAlertAction = UIAlertAction(title: "Camera".localized, style: .default, handler: {(cameraAction) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) == true {
if self.isCamAccessDenied() == false { **//Calling cam access method here**
imagePicker.sourceType = .camera
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}
}else{
self.present(self.showAlert(Title: "", Message: "Camera is not available on this Device or accesibility has been revoked!".localized), animated: true, completion: nil)
self.showTabbar()
}
})
let libraryAction : UIAlertAction = UIAlertAction(title: "Photo Library", style: .default, handler: {(libraryAction) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) == true {
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}else{
self.showTabbar()
self.present(self.showAlert(Title: "", Message: "Photo Library is not available on this Device or accesibility has been revoked!".localized), animated: true, completion: nil)
}
})
let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel".localized, style: .cancel , handler: {(cancelActn) in
self.showTabbar()
})
alertController.addAction(cameraAction)
alertController.addAction(libraryAction)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.sourceView = view
alertController.popoverPresentationController?.sourceRect = view.frame
self.present(alertController, animated: true, completion: nil)
self.hideTabbar()
}
Method to handle camera access functionality
处理相机访问功能的方法
func isCamAccessDenied()-> Bool
{
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status == .restricted || status == .denied {
DispatchQueue.main.async
{
var alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Close this app.\n\n2. Open the Settings app.\n\n3. Scroll to the bottom and select this app in the list.\n\n4. Turn the Camera on.\n\n5. Open this app and try again."
var alertButton = "OK"
var goAction = UIAlertAction(title: alertButton, style: .default, handler: nil)
if UIApplication.shared.canOpenURL(URL(string: UIApplicationOpenSettingsURLString)!)
{
alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Touch the Go button below to open the Settings app.\n\n2. Turn the Camera on.\n\n3. Open this app and try again."
alertButton = "OK"
goAction = UIAlertAction(title: alertButton, style: .default, handler: {(alert: UIAlertAction!) -> Void in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
})
}
let alert = UIAlertController(title: "Error", message: alertText, preferredStyle: .alert)
alert.addAction(goAction)
self.present(alert, animated: true, completion: nil)
}
return true
}
return false
}