iOS中的各种权限

直接看代码吧

#pragma mark --- 获取用户相机权限 ---
/**
 获取用户的相机访问权限
 
 @param authorized 用户允许访问相机
 @param denied 用户拒绝当前应用访问相机
 @param restricted 因为系统原因, 无法访问相机
 @param noCamera 没有检测到相机
 @param firstRequestAllowed 第一次请求并被允许
 @param requestAuthorization 如果没有权限是否要立刻请求权限
 @return 是否已经授权
 */
- (BOOL)cameraAuthorizationTools_StatusAuthorizedBlock:(void (^)(void))authorized
                                     StatusDeniedBlock:(void (^)(void))denied
                                 StatusRestrictedBlock:(void (^)(void))restricted
                           EquipmentWithoutCameraBlock:(void (^)(void))noCamera
                                   firstRequestAllowed:(void (^)(void))firstRequestAllowed
                                  requestAuthorization:(BOOL)requestAuthorization {
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {                 //用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
            
            if (!requestAuthorization) {
                return NO;
            }
            
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 用户第一次同意了访问相机权限
                        if (firstRequestAllowed) {
                            firstRequestAllowed();
                        }
                    });

                } else {
                    // 用户第一次拒绝了访问相机权限
                    
                }
            }];
            
            return NO;
            
        } else if (status == AVAuthorizationStatusAuthorized) {             // 用户允许当前应用访问相机
            
            if (authorized) {
                authorized();
            }
            
            return YES;
            
        } else if (status == AVAuthorizationStatusDenied) {                 // 用户拒绝当前应用访问相机
            
            if (denied) {
                denied();
            }
            
            return NO;
            
        } else if (status == AVAuthorizationStatusRestricted) {             //因为系统原因, 无法访问相册
            
            if (restricted) {
                restricted();
            }
            
            return NO;
            
        } else {
            
            return NO;
        }
        
    } else {
       
        //未检测到摄像头
        if (noCamera) {
            noCamera();
        }
        
        return NO;
    }
}


#pragma mark  ---  获取相册权限  ---
/**
 获取相册权限
 
 @param authorized 用户允许访问相册
 @param denied 用户拒绝当前应用访问相册
 @param restricted 因为系统原因, 无法访问相册
 @param noPhoto 没有检测到相册
 @param firstRequestAllowed 第一次请求并被允许
 @param requestAuthorization 如果没有权限是否要立刻请求权限
 @return 是否已经授权
 */
- (BOOL)imagePickerStatus_AuthorizedBlock:(void(^)(void))authorized
                              DeniedBlock:(void(^)(void))denied
                          RestrictedBlock:(void(^)(void))restricted
                             noPhotoBlock:(void(^)(void))noPhoto
                      firstRequestAllowed:(void (^)(void))firstRequestAllowed
                     requestAuthorization:(BOOL)requestAuthorization {
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {                                       //用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
        if (!requestAuthorization) {
            return NO;
        }
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
            if (status == PHAuthorizationStatusAuthorized){//已经授权应用访问照片数据
                if (firstRequestAllowed) {
                    firstRequestAllowed();
                }
            }
        }];
        
        return NO;
        
    } else if(status == PHAuthorizationStatusAuthorized) {                                    //已经授权应用访问照片数据
       
        if (authorized) {
            authorized();
        }
        
        return YES;
    }else if(status == PHAuthorizationStatusDenied) {                                        //用户已经明确否认了这一照片数据的应用程序访问
        if (denied) {
            denied();
        }
        return NO;
    }else if (status == PHAuthorizationStatusRestricted) {                                    //此应用程序没有被授权访问的照片数据
        if (restricted) {
            restricted();
        }
        return NO;
    }else {
        
        //没有检测到有相册
        if (noPhoto) {
            noPhoto();
        }
        return NO;
    }
}


#pragma mark  ---   获取麦克风权限   ---

/**
 获取麦克风权限
 
 @param authorized 用户允许访问麦克风
 @param denied  用户拒绝当前应用访问麦克风
 @param restricted 因为系统原因, 无法访问麦克风
 @param noAudio 没有检测到麦克风
 @param firstRequestAllowed 第一次请求并被允许
 @param requestAuthorization 如果没有权限是否要立刻请求权限
 @return 是否已经授权
 */
- (BOOL)audioAuthorizationStatus_AuthorizedBlock:(void(^)(void))authorized
                                     DeniedBlock:(void(^)(void))denied
                                 RestrictedBlock:(void(^)(void))restricted
                                    noAudioBlock:(void(^)(void))noAudio
                             firstRequestAllowed:(void (^)(void))firstRequestAllowed
                            requestAuthorization:(BOOL)requestAuthorization {
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    
    if (status == AVAuthorizationStatusNotDetermined) {                     //用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
    
        if (!requestAuthorization) {
            return NO;
        }
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            if (granted) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                   //第一次授权后
                    if (firstRequestAllowed) {
                        firstRequestAllowed();
                    }
                });
                
            }else {
                // 用户第一次拒绝了访问权限
            }
        }];
        return NO;
        
    } else if (status ==   AVAuthorizationStatusAuthorized){                //已经授权应用访问麦克风
        
        if (authorized) {
            authorized();
        }
        return YES;
        
    } else if (status == AVAuthorizationStatusRestricted) {                 //此应用程序没有被授权访问的麦克风
        
        if (restricted) {
            restricted();
        }
        return NO;
        
    } else if (status == AVAuthorizationStatusDenied) {                     //用户拒绝当前应用访问麦克风
        
        if (denied) {
            denied();
        }
        return NO;
        
    } else {                                                                //没有检测到麦克风
        
        if (noAudio) {
            noAudio();
        }
        return NO;
        
    }
}



#pragma mark  ---   获取日历权限   ---
- (void)eventAuthorizationStatus_AuthorizedBlock:(void(^)(void))authorized
                                     DeniedBlock:(void(^)(void))denied
                                 RestrictedBlock:(void(^)(void))restricted
                                    noEventBlock:(void(^)(void))noEvent{
    
    EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
    switch (status) {
        case EKAuthorizationStatusNotDetermined:                    //用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
        {
            EKEventStore *store = [[EKEventStore alloc] init];
            if (store){
                [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError * _Nullable error) {
                    if (granted) {
                        //第一次授权后
                        
                    }else{
                        
                    }
                }];
            }
        }
            break;
            
        case EKAuthorizationStatusAuthorized:                               //已经授权应用访问日历
            if (authorized) {
                authorized();
            }
            break;
            
        case EKAuthorizationStatusRestricted:                               //此应用程序没有被授权访问的日历
            if (restricted) {
                restricted();
            }
            break;
            
        case EKAuthorizationStatusDenied:                                    //用户拒绝当前应用访问日历
            if (denied) {
                denied();
            }
            break;
        default:                                                             //没有检测到日历
            if (noEvent) {
                noEvent();
            }
            break;
    }
}

#pragma mark  ---   获取通讯录权限   ---
- (void)contactAuthorizationStatus_AuthorizedBlock:(void(^)(void))authorized
                                       DeniedBlock:(void(^)(void))denied
                                   RestrictedBlock:(void(^)(void))restricted
                                    noContactBlock:(void(^)(void))noContact{
    //这里有一个枚举类:CNEntityType,不过没关系,只有一个值:CNEntityTypeContacts
    //ios 9.0 之后版本
    if (@available(iOS 9.0, *)) {
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        
        if (status == CNAuthorizationStatusNotDetermined) {                         //用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
            
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            if (contactStore == NULL) {
                
            }
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                
                if (error) {
                }else{
                    if (granted) {
                        
                    }else{
                        
                    }
                }
            }];
            
        }else if (status == CNAuthorizationStatusAuthorized){                       //已经授权应用访问通讯录
            if (authorized) {
                authorized();
            }
        }else if (status == CNAuthorizationStatusRestricted) {                      //此应用程序没有被授权访问的通讯录
            if (restricted) {
                restricted();
            }
        }else if (status == CNAuthorizationStatusDenied) {                          //用户拒绝当前应用访问通讯录
            if (denied) {
                denied();
            }
        }else{
            if (noContact) {
                noContact();
            }
        }
    }else {
        //ios 9.0 之前版本
        ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
        
        if (status == kABAuthorizationStatusNotDetermined) {                            //用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
            
            __block ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
            if (addressBookRef == NULL) {
            }
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                if (granted) {
                }else{
                }
                if (addressBookRef) {
                    CFRelease(addressBookRef);
                    addressBookRef = NULL;
                }
            });
        }else if(status == kABAuthorizationStatusAuthorized){                           //已经授权应用访问通讯录
            if (authorized) {
                authorized();
            }
        } else if (status == kABAuthorizationStatusRestricted) {                        //此应用程序没有被授权访问的通讯录
            if (restricted) {
                restricted();
            }
        } else if (status == kABAuthorizationStatusDenied) {                            //用户拒绝当前应用访问通讯录
            if (denied) {
                denied();
            }
        } else {
            if (noContact) {
                noContact();
            }
        }
    }
    
}


#pragma mark  ---   获取定位权限   ---
/**
 获取定位权限
 
 @param always 用户允许应用一直允许访问定位
 @param WhenInUse 用户只允许在使用应用程序时访问定位
 @param Denied 用户拒绝当前应用访问定位权限
 @param Restricted 因为系统原因
 @param noLocation 没有检测到定位权限
 @param firstRequestAllowed 第一次请求并被允许
 @param requestAuthorization 如果没有权限是否要立刻请求权限
 @return 是否已经授权
 */
- (BOOL)locationAuthorizationStatus_AlwaysBlock:(void(^)(void))always
                                 WhenInUseBlock:(void(^)(void))WhenInUse
                                    DeniedBlock:(void(^)(void))Denied
                                RestrictedBlock:(void(^)(void))Restricted
                                noLocationBlock:(void(^)(void))noLocation
                            firstRequestAllowed:(void (^)(void))firstRequestAllowed
                           requestAuthorization:(BOOL)requestAuthorization {
    
    BOOL isLocationServicesEnabled = [CLLocationManager locationServicesEnabled];
    if (!isLocationServicesEnabled) {
        return NO;
    }else{
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
        
        if (status == kCLAuthorizationStatusNotDetermined) {                            //第一次获取定位
           
            if (!requestAuthorization) {
                return NO;
            }
            
            [self startLocation];
            return NO;
        } else if (status == kCLAuthorizationStatusAuthorizedAlways) {                   //授权应用可以一直获取定位
            if (always) {
                always();
            }
            return YES;
        } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {                //授权当前应用在使用中获取定位
            if (WhenInUse) {
                WhenInUse();
            }
            return YES;
        } else if (status == kCLAuthorizationStatusDenied) {                             //用户拒绝当前应用访问获取定位
            if (Denied) {
                Denied();
            }
            return NO;
        } else if (status == kCLAuthorizationStatusRestricted) {                         //此应用程序没有被授权访问的获取定位
            if (Restricted) {
                Restricted();
            }
            return NO;
        } else {                                                                          // kCLAuthorizationStatusAuthorized < ios8
            
            if (noLocation) {
                noLocation();
            }
            return NO;
        }
    }
}

#pragma mark Location and Delegate
- (void)startLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    
    /** 由于IOS8中定位的授权机制改变 需要进行手动授权
     * 获取授权认证,两个方法:
     * [self.locationManager requestWhenInUseAuthorization];
     * [self.locationManager requestAlwaysAuthorization];
     */
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

        [self.locationManager requestWhenInUseAuthorization];
        //[self.locationManager requestAlwaysAuthorization];
    }
    
    
    //开始定位,不断调用其代理方法
    //[self.locationManager startUpdatingLocation];
    //DLog(@"start gps");
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    // 1.获取用户位置的对象
    //CLLocation *location = [locations lastObject];
    //CLLocationCoordinate2D coordinate = location.coordinate;
    //DLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
    
    //NSNumber *longitute = [NSNumber numberWithDouble:coordinate.longitude];
    //NSNumber *latitude = [NSNumber numberWithDouble:coordinate.latitude];
    
    // 2.停止定位
    //[manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusAuthorizedAlways: {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AuthorizationStatusAuthorizedAlways" object:nil];
        }
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse: {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AuthorizedWhenInUsePermissionChanged" object:nil];
        }
            break;
        case kCLAuthorizationStatusDenied: DLog(@"Denied");
            break;
            
        case kCLAuthorizationStatusNotDetermined: DLog(@"not Determined");
            break;
            
        case kCLAuthorizationStatusRestricted: DLog(@"Restricted");
            break;
        default: break;
    }
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
    }
}

@end

可参考的文章

你可能感兴趣的:(iOS中的各种权限)