iOS 权限判断及跳转设置

2018-03-26  本文已影响218人  云天涯丶

iPhone相册、相机权限是个老生常谈的话题,最近项目种涉及到了权限及提示跳转,下面是整理的一些资料。

环境:

编译器:Xcode 9.2
iPhone:10.3.3、11.2.1

1、添加权限

<key>NSCameraUsageDescription</key>
<string>上传个人头像会使用相机功能</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>上传个人头像会使用相册功能</string>

2、判断权限

// 相机权限 需要导入#import <AVFoundation/AVCaptureDevice.h>
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied){// 指引开启
            
[self.view alertController:self title:nil message:@"请在iPhone的“设置-隐私-相机”选项中,允许访问你的相机" sureTitle:@"好的" cancelTitle:@"设置" sureHandler:^(UIAlertAction * _Nonnull action) {
            
 } cancelHandler:^(UIAlertAction * _Nonnull action) {
               
}

// 相册权限  需要导入#import <Photos/PHPhotoLibrary.h>
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){
            
[self.view alertController:self title:nil message:@"请在iPhone的“设置-隐私-照片”选项中,允许访问你的相册" sureTitle:@"好的" cancelTitle:@"设置" sureHandler:^(UIAlertAction * _Nonnull action) {
                
} cancelHandler:^(UIAlertAction * _Nonnull action) {
              
}

3、跳转设置界面

有3种跳转的方式
方式一:prefs:root=某项服务
方式二:prefs:root=bundleID
方式三: UIApplicationOpenSettingsURLString

前两项用openURL,返回error,网上找了很多方法(比如:设置URL Scheme),都不成功;后来发现iOS 10可以这样设置:

NSURL *url = [NSURL URLWithString:@"App-Prefs:root=bundle id"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
     [[UIApplication sharedApplication] openURL:url];
}

还有一种:(貌似审核过不了)

NSURL *url = [NSURL URLWithString:@"Prefs:root=bundle id"];
Class LSApplicationWorkspace = NSClassFromString(@"LSApplicationWorkspace");
[[LSApplicationWorkspace performSelector:@selector(defaultWorkspace)] performSelector:@selector(openSensitiveURL:withOptions:) withObject:url withObject:nil];

iOS 11,用下面的方法:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

注:经测试,有些机器系统10.3.3用 UIApplicationOpenSettingsURLString 可以进入app权限设置,有些不可以。。。

相关资料:
https://www.jianshu.com/p/4ae5189be228
https://stackoverflow.com/questions/39782510/open-wifi-settings-by-prefsroot-wifi-failed-in-ios-10

上一篇下一篇

猜你喜欢

热点阅读