我们都去过那里。你想在你的应用程序中拍照,或者访问照片、麦克风、联系人等……但首先 iOS 必须提示用户许可。在许多情况下,用户会拒绝访问。
如果您的应用检测到用户拒绝访问,您可以使用以下命令将用户导航到应用的隐私设置:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
便利。然而....
我注意到,如果您确实说服用户将开关切换到打开,则该应用程序不会检测到更改。
考虑这段代码。立即提示用户访问相机的权限(这仅显示该应用程序第一次运行)。假设用户拒绝了权限。接下来,他们决定他们确实想要启用相机访问权限。没问题。用户点击弹出隐私面板的按钮。用户更改开关以允许访问。然后用户切换回应用程序。该块触发 UIApplicationDidBecomeActiveNotification 再次读取权限。但是,它不反映用户的更改(仍读作 Denied)。
如果应用程序从内存中清除并再次运行,它将正确读取状态。
并非所有权限都以这种方式运行。例如 CoreLocation 似乎可以检测到用户的更改。我还找到了一种检测通知更改的方法。但是对于通讯录、日历、相机、麦克风、Core Motion(等等),在应用程序终止并再次运行之前不会检测到更改。
有任何想法吗?
#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