我们都曾经遇到过这种情况。你想在你的应用程序中拍照,或者访问照片、麦克风、联系人等等... 但是首先iOS必须提示用户授权。在许多情况下,用户会拒绝授权。
如果你的应用程序检测到用户已经拒绝了访问权限,你可以使用以下代码将用户引导到应用程序的隐私设置页面:
如果你的应用程序检测到用户已经拒绝了访问权限,你可以使用以下代码将用户引导到应用程序的隐私设置页面:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
方便,但是....
我注意到,如果您成功说服用户切换到开启状态,则应用程序无法检测更改。
考虑以下代码。立即提示用户允许访问相机(仅在第一次运行应用程序时显示此项)。假设用户拒绝了权限。接下来,他们决定还是要启用相机访问。没问题。用户点击按钮,打开隐私面板。用户更改开关以允许访问。然后用户切回应用程序。块会触发UIApplicationDidBecomeActiveNotification,再次读取权限。但它不反映用户的更改(仍然读为被拒绝)。
如果从内存中清除该应用程序并重新运行,它将正确读取状态。
并非所有权限都表现出这种行为。例如CoreLocation似乎可以检测到用户的更改。我还找到了一种检测通知更改的方法。但是对于联系人、日历、相机、麦克风、核心动作(等等),直到重新启动应用程序,才能检测到更改。
有什么想法吗?
#import "ViewController.h"
@import AVFoundation;
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[self printPermission];
}];
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
[self printPermission];
}];
}
-(void)printPermission{
dispatch_async(dispatch_get_main_queue(), ^{
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if(status == AVAuthorizationStatusNotDetermined){
NSLog(@"VWWPermissionStatusNotDetermined");
self.view.backgroundColor = [UIColor whiteColor];
} else if(status == AVAuthorizationStatusAuthorized){
NSLog(@"VWWPermissionStatusAuthorized");
self.view.backgroundColor = [UIColor greenColor];
} else if(status == AVAuthorizationStatusDenied) {
NSLog(@"VWWPermissionStatusDenied");
self.view.backgroundColor = [UIColor redColor];
} else if(status == AVAuthorizationStatusRestricted) {
NSLog(@"VWWPermissionStatusRestricted");
self.view.backgroundColor = [UIColor redColor];
}
});
}
- (IBAction)buttonAction:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
@end
viewDidAppear
中测试授权是有效的。例如:https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch19p725calendar/ch32p986calendar/ViewController.swift 在我的测试中,如果我们将用户发送到设置应用并且用户授予权限,则可以正常工作。 - matt