您的位置:首页 > 移动开发 > IOS开发

判断是否开启相机相册、定位权限并去系统开启权限

2018-03-26 10:20 429 查看
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, ChosePhontType) {    ChosePhontTypeAlbum,  //相册    ChosePhontTypeCamera   //相机};
@interface AuthorityManage : NSObject
@property (nonatomic, strong) CLLocationManager *locationManager; //定位管理类
+ (instancetype)sharedManager;
- (void)chosePhoto:(ChosePhontType)type picker:(UIImagePickerController *)picker vc:(UIViewController *)vc;
- (void)savePhotoToAlbumWithImage:(UIImage *)image vc:(UIViewController *)vc;
- (void)setLocationManageWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy                              distanceFilter:(CLLocationDistance)distanceFilter                                          vc:(UIViewController *)vc;
@end

#import "AuthorityManage.h"#import <Photos/PHPhotoLibrary.h>#import <AVFoundation/AVCaptureDevice.h>#import <AVFoundation/AVMediaFormat.h>//    kCLAuthorizationStatusNotDetermined   //用户尚未做出选择这个应用程序的问候//    kCLAuthorizationStatusRestricted  //此应用程序没有被授权访问的照片数据。可能是家长控制权限//    kCLAuthorizationStatusDenied  //用户已经明确否认了这一照片数据的应用程序访问//    kCLAuthorizationStatusAuthorized  //用户已经授权应用访问照片数据
@implementation AuthorityManage
// 创建单例对象+ (instancetype)sharedManager{    static dispatch_once_t token;    static AuthorityManage * manage = nil;        dispatch_once(&token, ^{        if (!manage) {            manage = [[AuthorityManage alloc] init];        }    });    return manage;}
//==========访问系统  相册 / 相机  ===============- (void)chosePhoto:(ChosePhontType)type picker:(UIImagePickerController *)picker vc:(UIViewController *)vc{    if (type == ChosePhontTypeAlbum) {   // 相册        //======判断 访问相册 权限是否开启=======        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];        //有被授权访问的照片数据   用户已经明确否认了这一照片数据的应用程序访问        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {            //====没有权限====            [[AuthorityManage sharedManager] showNoAlbumAuthalertControllerWithVC:vc type:ChosePhontTypeAlbum];        } else {    //====有访问相册的权限=======            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {   //相册可用                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;                [vc presentViewController:picker animated:YES completion:^{}];            } else {  // 相册不可用                NSLog(@"相册不可用");            }        }    } else if (type == ChosePhontTypeCamera) {  // 相机        //======判断 访问相机 权限是否开启=======        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){            //====无权限====            [[AuthorityManage sharedManager] showNoAlbumAuthalertControllerWithVC:vc type:ChosePhontTypeCamera];        } else {            //===有权限======            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {   //相机可用                picker.sourceType = UIImagePickerControllerSourceTypeCamera;                [vc presentViewController:picker animated:YES completion:^{}];            } else {  // 相机不可用                NSLog(@"相机不可用");
            }        }    }}
- (void)showNoAlbumAuthalertControllerWithVC:(UIViewController *)vc type:(ChosePhontType)type{    NSString *title;    NSString *message;    if (type == ChosePhontTypeAlbum) {        title = @"开启相册权限";        message = @"开启后才能访问你的相册";    } else {        title = @"开启相机权限";        message = @"开启后才能访问你的相机";    } UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];   UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {            }];    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {        //===无权限 引导去开启===        [[AuthorityManage sharedManager] openJurisdiction];    }];    [alertController addAction:cancel];    [alertController addAction:ok];    [vc presentViewController:alertController animated:YES completion:nil];}
#pragma mark-------去设置界面开启权限----------- (void)openJurisdiction{    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];    if ([[UIApplication sharedApplication] canOpenURL:url]) {        if (kSystemVersion > 10.0) {            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];        } else {            [[UIApplication sharedApplication] openURL:url];        }    }}
- (void)savePhotoToAlbumWithImage:(UIImage *)image vc:(UIViewController *)vc{    if (@available(iOS 11.0, *)) {        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {            if (status == PHAuthorizationStatusNotDetermined || status == PHAuthorizationStatusAuthorized) {                //保存图片到相册                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);            } else {                //====没有权限====                [[AuthorityManage sharedManager] showNoAlbumAuthalertControllerWithVC:vc type:ChosePhontTypeAlbum];            }        }];    } else {        //======判断 访问相册 权限是否开启=======        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];        //有被授权访问的照片数据   用户已经明确否认了这一照片数据的应用程序访问        //家长控制,不允许访问 || 用户拒绝当前应用访问相册        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {            //====没有权限====            [[AuthorityManage sharedManager] showNoAlbumAuthalertControllerWithVC:vc type:ChosePhontTypeAlbum];        } else {    //====有访问相册的权限=======            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {   //相册可用                //因为需要知道该操作的完成情况,即保存成功与否,所以此处需要一个回调方法image:didFinishSavingWithError:contextInfo:                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);            } else {  // 相册不可用                NSLog(@"相册不可用");            }        }    }}
//保存相册回调方法- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{    NSString *msg = nil ;    if (error != NULL) {        msg = @"保存图片失败" ;    } else {        msg = @"保存图片成功" ;    }    [Common showToastMsg:msg];}
- (void)setLocationManageWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy                              distanceFilter:(CLLocationDistance)distanceFilter                                          vc:(UIViewController *)vc{    //判断定位是否开启是判断的整个手机系统的定位是否打开,并不是针对这一应用    //判断手机定位是否开启    if([CLLocationManager locationServicesEnabled]) {        //用户第一次下载应用需要先调用定位去系统注册 才能弹出是否允许定位的系统提示框        BOOL isRequestLocation = [[NSUserDefaults standardUserDefaults] boolForKey:kIsRequestLocationAuth];        if (!isRequestLocation) {            [self requestLocationWithDesiredAccuracy:desiredAccuracy distanceFilter:distanceFilter vc:vc];        } else {            //判断用户是否禁止当前应用获取位置权限  永不、使用应用期间、始终            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||                [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {                //用户允许获取位置权限                [self requestLocationWithDesiredAccuracy:desiredAccuracy distanceFilter:distanceFilter vc:vc];            } else {                //用户拒绝开启用户权限                [Common showSystemAlertWithtitle:@"打开定位服务来允许xxx确定您的位置"                                         message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>xxx>使用应用期间)"                                      okBtnTitle:去开启                                  viewController:vc                               alertOkBtnClicked:^(UIAlertAction *action) {                    //引导去开启                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];                    if( [[UIApplication sharedApplication] canOpenURL:url] ) {                        [[UIApplication sharedApplication] openURL:url];                    }                }];            }        }    } else {        //手机未开启权限        [Common showNormalAlert:@"在系统设置中开启定位服务来允许xxx确定您的位置"              andViewController:vc              alertOkBtnClicked:^(UIAlertAction *action) { }];    }}
- (void)requestLocationWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy                            distanceFilter:(CLLocationDistance)distanceFilter                                        vc:(UIViewController *)vc{    [AuthorityManage sharedManager].locationManager.desiredAccuracy = desiredAccuracy;    [AuthorityManage sharedManager].locationManager.distanceFilter = distanceFilter;    if (kSystemVersion >= 8) {        [[AuthorityManage sharedManager].locationManager requestWhenInUseAuthorization]; //使用程序其间允许访问位置数据(iOS8定位需要)    }    [[AuthorityManage sharedManager].locationManager startUpdatingLocation]; //开启定位    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsRequestLocationAuth]; //是否注册过定位权限    [[NSUserDefaults standardUserDefaults] synchronize];}
- (CLLocationManager *)locationManager{    if (!_locationManager) {        _locationManager = [[CLLocationManager alloc] init];    }    return _locationManager;}

//调用
[[AuthorityManage sharedManager] savePhotoToAlbumWithImage:Image vc:self];[[AuthorityManage sharedManager] chosePhoto:ChosePhontTypeCamera picker:self.pickV vc:self];

#pragma mark - 地图定位
- (void)requestLocation{    [AuthorityManage sharedManager].locationManager.delegate = self;    [[AuthorityManage sharedManager] setLocationManageWithDesiredAccuracy:kCLLocationAccuracyThreeKilometers distanceFilter:100 vc:self];}-(void)dealloc{   //防止回调崩溃   [AuthorityManage sharedManager].locationManager.delegate = nil;}
#pragma mark - CLLocationManagerDelegate-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{    CLLocation *location = [locations lastObject];    //获取WGS-84坐标的对象,两者选其一    CLLocationCoordinate2D coords = location.coordinate;    //获得经纬度    NSLog(@"纬度%f,经度%f",coords.latitude,coords.longitude);    //停止定位    [[AuthorityManage sharedManager].locationManager stopUpdatingLocation];}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{    if ([error code] == kCLErrorDenied) {        NSLog(@"访问被拒绝");    }    if ([error code] == kCLErrorLocationUnknown) {        NSLog(@"无法获取位置信息");    }}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS