ios基础知识iOS开发小技巧iOS 基础知识

iOS系统访问权限(通讯录、相机、相册、麦克风、定位)

2017-05-04  本文已影响858人  摸着石头过河_崖边树

前言####

大家都知道苹果他老人家很注重用户的隐私保护,所以我们一般在访问用户的隐私(比如相册、相机)的时候都需要用户授权,那么您真的了解用户授权吗?今天小编就细细道来。

自问自答####

关于授权的几个问题
1、系统访问授权是必须要设置的吗?怎么设置?
答:是的,如果没有,iOS10.0之后会崩溃的,崩溃信息如下

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.

解决办法:
只要在info.plist里面设置对应信息就可以了


Snip20170404_9.pngSnip20170404_9.png

2、系统默认的弹框怎么来的?
答:只要在info.plist文件中设置了您需要访问的参数(key 和NSString),就会有默认弹框,温馨提示:弹框的文字内容要注意编写,否则会被拒绝哦

<key>NSMicrophoneUsageDescription</key>
<string>xxxapp需要访问您的麦克风(弹框文字)</string>

3、用户第一次授权点击不允许怎么办?
A方案:我们自定义一个弹框,提示用户要设置授权

[self showWithMessage:@"此功能需要您授权本App打开相机\n设置方法:打开手机设置->隐私->相机"];  
   //弹框提示
+ (void)showWithMessage:(NSString *)tipString
{
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:tipString delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alter show];
}

B方案:直接跳转到设置页面设置隐私

   //引导到设置页面去设置
+ (void)gotoSetting
{
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication]canOpenURL:url]) {
    [[UIApplication sharedApplication]openURL:url];
}
}
 /**
  跳转到设置权限界面
  */
+ (void)gotoSettingPrivacyWithType:(LZBAppSettingType)type
{
NSString *jumpString =LZBAppSettingTypeValue[type];
if(jumpString.length == 0)
{
    [self gotoSetting];
    return;
}
NSURL *url = [NSURL URLWithString:jumpString];
if ([[UIApplication sharedApplication]canOpenURL:url]) {
    [[UIApplication sharedApplication]openURL:url];
}

}

注意:小编提醒,iOS10.0之前Prefs:root=General&path=CAMERA系列还有用,但是iOS10.0之后没有用了,可以直接使用UIApplicationOpenSettingsURLString就可以跳转到对应的设置页面

相机授权####

1、导入框架 #import <AVFoundation/AVFoundation.h>

2、检测授权,如果是第一次那么状态肯定是AVAuthorizationStatusNotDetermined,此时我们要点击系统弹框,并且调用+ (void)requestAccessForMediaType:(NSString *)mediaType completionHandler:(void (^)(BOOL granted))handler 检测点击授权与否,如果点击不允许,那么我们就可以采用上述的A和B方案

 /**
 检测录制视频的相机是否授权
  */
+ (BOOL)checkVideoCameraAuthorization
{
__block BOOL isAvalible = NO;
__weak __typeof__(self) weakSelf = self;
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
switch (status) {
    case AVAuthorizationStatusAuthorized: //授权
        isAvalible = YES;
        break;
    case AVAuthorizationStatusDenied:   //拒绝,弹框
        {
           [self showWithMessage:@"此功能需要您授权本App打开相机\n设置方法:打开手机设置->隐私->相机"];
            isAvalible = NO;
        }
        break;
    case AVAuthorizationStatusNotDetermined:   //没有决定,第一次启动默认弹框
    {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            isAvalible = granted;
            if(!granted)  //如果不允许
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf gotoSetting];
                });
            }
        }];
    }
        break;
    case AVAuthorizationStatusRestricted:  //受限制,家长控制器
        isAvalible = NO;
        break;
}
return isAvalible;

}

3、注意在info.plist设置第一次弹框的文字内容

<key>NSCameraUsageDescription</key>
<string>xxxapp需要访问您的照相机</string>

麦克风授权####

1.导入#import <AVFoundation/AVFoundation.h>

2、方法和检测相机差不多,只是把类型换成AVMediaTypeAudio。检测授权,如果是第一次那么状态肯定是AVAuthorizationStatusNotDetermined,此时我们要点击系统弹框,并且调用+ (void)requestAccessForMediaType:(NSString *)mediaType completionHandler:(void (^)(BOOL granted))handler 检测点击授权与否,如果点击不允许,那么我们就可以采用上述的A和B方案

  /**
 检测录制视频的麦克风是否授权
 */
+ (BOOL)checkVideoMicrophoneAudioAuthorization
{
 __block BOOL isAvalible = NO;
 __weak __typeof__(self) weakSelf = self;
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
switch (status) {
    case AVAuthorizationStatusAuthorized: //授权
        isAvalible = YES;
        break;
    case AVAuthorizationStatusDenied:   //拒绝,弹框
        {
            [self showWithMessage:@"此功能需要您授权本App打开麦克风\n设置方法:打开手机设置->隐私->麦克风"];
            isAvalible = NO;
        }
        break;
    case AVAuthorizationStatusNotDetermined:   //没有决定,第一次启动
        {
            //点击弹框授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                isAvalible = granted;
                if(!granted)  //如果不允许
                {
                    //回到主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                         [weakSelf gotoSetting];
                    });
                }
            }];
        }
        break;
    case AVAuthorizationStatusRestricted:  //受限制,家长控制器
       isAvalible = NO;
        break;
}
return isAvalible;
}

3、注意在info.plist设置第一次弹框的文字内容

<key>NSMicrophoneUsageDescription</key>
<string>xxxapp需要访问您的麦克风</string>

相册授权####

1、iOS8.0之后,导入#import <Photos/Photos.h>

2、检测授权,如果是第一次那么状态肯定是PHAuthorizationStatusNotDetermined,此时我们要点击系统弹框,并且调用+ (void)requestAuthorization:(void(^)(PHAuthorizationStatus status))handler检测点击授权与否,如果点击不允许,那么我们就可以采用上述的A和B方案

  /**
   检测相册是否授权
 */
 + (BOOL)checkVideoPhotoAuthorization
{
__block BOOL isAvalible = NO;
__weak __typeof__(self) weakSelf = self;
//iOS8.0之后
PHAuthorizationStatus photoStatus =  [PHPhotoLibrary authorizationStatus];
switch (photoStatus) {
    case PHAuthorizationStatusAuthorized:
        isAvalible = YES;
        break;
    case PHAuthorizationStatusDenied:
    {
        [self showWithMessage:@"此功能需要您授权本App打开相册\n设置方法:打开手机设置->隐私->相册"];


        isAvalible = NO;
    }
        break;
    case PHAuthorizationStatusNotDetermined:
    {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                isAvalible = YES;
            }else{
                isAvalible = NO;  //回到主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf gotoSetting];
                });
            }
        }];   
    }
        break;
    case PHAuthorizationStatusRestricted:
        isAvalible = NO;
        break;
    default:
        break;
   }
   return isAvalible;
  };

3、注意在info.plist设置第一次弹框的文字内容

 <key>NSPhotoLibraryUsageDescription</key>
<string>xxxapp需要访问您的照片管理器</string>

通讯录授权####

1、导入框架
iOS9.0之前导入#import <AddressBook/AddressBook.h>
iOS9.0之后导入#import <Contacts/Contacts.h>

2、方法还是检测授权状态,如果第一次启动还是未决定,此时弹框系统默认的框,调用方法监听点击结果(允许还是不允许),如果是不允许,还是采用A或B方案

// 检测通讯录是否授权
 + (BOOL)checkContactsAuthorization
{
__block BOOL isAvalible = NO;
__weak __typeof__(self) weakSelf = self;
//iOS9.0之前
if([[UIDevice currentDevice].systemVersion floatValue] <= __IPHONE_9_0)
{
    ABAuthorizationStatus authorStatus = ABAddressBookGetAuthorizationStatus();
    switch (authorStatus) {
        case kABAuthorizationStatusAuthorized:
            isAvalible = YES;
            break;
        case kABAuthorizationStatusDenied:
        {
            [self showWithMessage:@"此功能需要您授权本App打开相册\n设置方法:打开手机设置->隐私->通讯录"];
            isAvalible = NO;
        }
            break;
        case kABAuthorizationStatusNotDetermined:
        {
            __block ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
            if (addressBook != NULL)
            {
                ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                    isAvalible = granted;
                    if (!granted) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                             [weakSelf gotoSetting];
                        });
                    }
                    if (addressBook) {
                        CFRelease(addressBook);
                        addressBook = NULL;
                    }
                });
            }
        }
            break;
        case kABAuthorizationStatusRestricted:
            isAvalible = NO;
            break;
        default:
            break;
    }
}
else//iOS9.0之后
{
    CNAuthorizationStatus authStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (authStatus) {
        case CNAuthorizationStatusAuthorized:
            isAvalible = YES;
            break;
        case CNAuthorizationStatusDenied:
        {
            [self showWithMessage:@"此功能需要您授权本App打开相册\n设置方法:打开手机设置->隐私->通讯录"];
            isAvalible = NO;
        }
            break;
        case CNAuthorizationStatusNotDetermined:
        {
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                isAvalible = granted;
                if (!granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                         [weakSelf gotoSetting];
                    });
                }
            }];
        }
            break;
        case CNAuthorizationStatusRestricted:
            isAvalible = NO;
            break;
    }
}
  return isAvalible;
 }

3、注意在info.plist设置第一次弹框的文字内容

<key>NSContactsUsageDescription</key>
<string>xxxapp需要访问您的通讯录</string>

定位授权####

1、导入#import <CoreLocation/CoreLocation.h>,注意不是#import <CoreLocation/CLLocationManager.h>

2、定位授权不一样,首先是检测当前定位状态,同样第一次都是kCLAuthorizationStatusNotDetermined未决定,但是定位授权是
requestWhenInUseAuthorization、requestAlwaysAuthorization这两个方法,并且监听方式是采用代理的方式监听

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status

这里只是监听的介绍定位授权,定位具体信息都要结合具体的项目使用

  + (BOOL)checkLocationAuthorization
  {
__block BOOL isAvalible = NO;
  if(![CLLocationManager locationServicesEnabled])
   return NO;
  CLAuthorizationStatus locationStatus =  [CLLocationManager authorizationStatus];
switch (locationStatus) {
    case kCLAuthorizationStatusAuthorizedAlways:
        isAvalible = NO;
        break;
    case kCLAuthorizationStatusNotDetermined:
    {
        isAvalible = NO;
    }
        break;
    case kCLAuthorizationStatusRestricted:
        isAvalible = NO;
        break;
    case kCLAuthorizationStatusDenied:
    {
        [self showWithMessage:@"此功能需要您授权本App打开相册\n设置方法:打开手机设置->隐私->位置信息"];
        isAvalible = NO;
    }
        break;
    case kCLAuthorizationStatusAuthorizedWhenInUse:
        isAvalible = YES;
        break;  
    default:
        break;
}
return isAvalible;

}

3、注意在info.plist设置第一次弹框的文字内容

 <key>NSLocationWhenInUseUsageDescription</key>
<string>xxxapp需要访问获取您的位置信息</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>xxxapp需要访问一直获取您的位置信息</string>

我已经把检测代码封装LZBAuthorizationManger成工具类可以使用到任意的项目,低耦合

源码下载地址:自定义视频录制方法之最优方案

最后赠言###

如果觉得文章对您有帮助,不要忘记star哦!😝,star 是对程序猿最大的鼓励!

上一篇下一篇

猜你喜欢

热点阅读