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

iOS 关于手机权限的检查与获取

2017-08-08 15:13 323 查看
手机通讯录权限:

/**

 *  检测权限并作响应的操作

 */

- (void)checkAuthorizationStatus:(UISwitch *)sender {

    

    switch (ABAddressBookGetAuthorizationStatus()) {

            

        case kABAuthorizationStatusAuthorized: //存在权限

            //获取通讯录

            self.phonesAry = [self obtainContacts:self.addressBook];

            if (_setAddBookBlock) {

                _setAddBookBlock(sender.isOn ? 0 : 1, _phonesAry);

            }

            break;

            

        case kABAuthorizationStatusNotDetermined: //权限未知

            //请求权限

            [self requestAuthorizationStatus:sender];

            break;

            

        case kABAuthorizationStatusDenied: //如果没有权限  需要提示

        case kABAuthorizationStatusRestricted:

            //弹窗提醒

        {

            

            NSString *appName = kApp_Display_Name;

            

            UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"%@没有获取手机通讯录的权限",appName] message:[NSString stringWithFormat:@"请在“[设置]-[隐私]-[通讯录]”里允许%@使用",appName] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,
nil];

            

            [alertview show];

            

            //重置开关

            dispatch_async(dispatch_get_main_queue(), ^{

                

                [sender setOn:NO];

                

                

            });

            

        }

            break;

            

        default:

            break;

    }

}

/**

 *  请求通讯录的权限

 */

- (void)requestAuthorizationStatus:(UISwitch *)sender {

    

    WeakSelf(self);

    

    ABAddressBookRequestAccessWithCompletion(self.addressBook, ^(bool granted, CFErrorRef error) {

        

        //权限得到允许

        if (granted == true) {

            dispatch_async(dispatch_get_main_queue(), ^{

                

                [sender setOn:YES];

                weakSelf.phonesAry = [weakSelf obtainContacts:weakSelf.addressBook];

                if (weakSelf.setAddBookBlock) {

                    weakSelf.setAddBookBlock(sender.isOn ? 0 : 1, weakSelf.phonesAry);

                }

                

            });

            

        } else {

            //不允许

            dispatch_async(dispatch_get_main_queue(), ^{

                

                [sender setOn:NO];

                

            });

            

        }

        

        

        

    });

}

/**

 *  获取通讯录中的联系人

 */

- (NSMutableArray *)obtainContacts:(ABAddressBookRef)addressBook {

    

    //按照添加时间请求所有的联系人

    CFArrayRef contants = ABAddressBookCopyArrayOfAllPeople(addressBook);

    

    //存放所有联系人电话号码的数组

    NSMutableArray *allNumArray = [NSMutableArray arrayWithCapacity:0];

    

    //遍历获取所有的数据

    for (NSInteger i = 0; i < CFArrayGetCount(contants); i++) {

        //获得People对象

        ABRecordRef recordRef = CFArrayGetValueAtIndex(contants, i);

        

        NSArray *contact = [self contactPhonePropertyWithRecordRef:recordRef];

        

        //添加对象

        [allNumArray addObjectsFromArray:contact];

    }

    

    //释放资源

    CFRelease(contants);

    

    return allNumArray;

    

}

//获取单个联系人的电话号码数组

- (NSArray *)contactPhonePropertyWithRecordRef:(ABRecordRef)recordRef {

    //外传数组

    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];

    

    //获得电话号码的多值对象

    ABMultiValueRef values = ABRecordCopyValue(recordRef, kABPersonPhoneProperty);

    

    for (NSInteger i = 0; i < ABMultiValueGetCount(values); i++) {

        

        //电话号码

        NSString *phoneNumber = (__bridge NSString *)ABMultiValueCopyValueAtIndex(values, i);

        

        //添加数据

        [phones addObject:phoneNumber];

        

    }

    

    //释放资源

    CFRelease(values);

    

    return [NSArray arrayWithArray:phones];

}

相机权限:

//检查相机权限

- (void)checkVideoStatus {

    

    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    switch (authStatus) {

        case AVAuthorizationStatusNotDetermined:

            //没有询问是否开启相机

            

            break;

        case AVAuthorizationStatusRestricted:

            //未授权,家长限制

            

            break;

        case AVAuthorizationStatusDenied:

            //未授权

            

            break;

        case AVAuthorizationStatusAuthorized:

            //玩家授权

            

            break;

        default:

            break;

    }

}

//授权相机

- (void)videoAuthAction {

    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {

        if (granted) {

            //相机准许

            

        } else {

            //相机不准许

            

        }

    }];

}

麦克风权限:

//检查麦克风权限

- (void)checkAudioStatus {

    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];

    switch (authStatus) {

        case AVAuthorizationStatusNotDetermined:

            //没有询问是否开启麦克风

            

            break;

        case AVAuthorizationStatusRestricted:

            //未授权,家长限制

            

            break;

        case AVAuthorizationStatusDenied:

            //玩家未授权

            

            break;

        case AVAuthorizationStatusAuthorized:

            //玩家授权

            

            break;

        default:

            break;

    }

}

//授权麦克风

- (void)audioAuthAction {

    

    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {

        

        if (granted) {

            //麦克风准许

            

        } else {

            //麦克风不准许

            

        }

    }];

}

照片权限:

//检查照片权限

- (void) checkPhotoStauts{

    PHAuthorizationStatus photoAuthorStatus = [PHPhotoLibrary authorizationStatus];

    switch (photoAuthorStatus) {

        case PHAuthorizationStatusAuthorized:

            

            break;

        case PHAuthorizationStatusDenied:

            

            break;

        case PHAuthorizationStatusNotDetermined:

            

            break;

        case PHAuthorizationStatusRestricted:

            

            break;

        default:

            break;

    }

}

//授权照片

- (void)phontLibraryAction{

    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

        

        dispatch_async(dispatch_get_main_queue(), ^{

            

            if (status == PHAuthorizationStatusAuthorized) {

                

                //照片允许

                

            } else {

                

                [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@没有使用照片的权限",kApp_Display_Name] message:[NSString stringWithFormat:@"请在“[设置]-[隐私]-[照片]”里允许%@使用",kApp_Display_Name] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil]
show];

                

            }

            

        });

        

    }];
}

定位权限:

位置定位相关资料: http://www.jianshu.com/p/98142b9edda0

//实例化

+ (instancetype)shareInstance {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [[LocationManager alloc] init];

    });

    return _instance;

}

- (instancetype)init {

    if (self = [super init]) {

        //定位管理器

        _locationManager = [CLLocationManager new];

        _geocoder        = [CLGeocoder new];

    }

    

    return self;

}

//设置定位管理

- (void)setLocationManager {

    

    if (![CLLocationManager locationServicesEnabled]) {

        DLog(@"定位信息没有开启");

    };

    

    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {

        

        if ([DeviceInfo getCurrentDeviceVersion] >= 8) {

            [_locationManager requestWhenInUseAuthorization];//?只在前台开启定位

            //[_locationManager requestAlwaysAuthorization];//?在后台也可定位

        }

        // 5.iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。

//            if ([DeviceInfo getCurrentDeviceVersion] >= 9) {

//                _locationManager.allowsBackgroundLocationUpdates = YES;

//            }

    } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {

        //设置代理

        _locationManager.delegate = self;

        //设置定位精度

        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;

        //定位频率,每隔多少米定位一次

        CLLocationDistance distance      = 100;//百米定位一次

        _locationManager.distanceFilter  = distance;

        

        //启动跟踪定位

        [_locationManager startUpdatingLocation];

    }

}

#pragma mark - CoreLocation 代理

#pragma mark 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)

//可以通过模拟器设置一个虚拟位置,否则在模拟器中无法调用此方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *location = [locations firstObject];//取出第一个位置

    CLLocationCoordinate2D coordinate = location.coordinate;//位置坐标

    

    _longitude = [NSString stringWithFormat:@"%f",coordinate.longitude];

    _latitude  = [NSString stringWithFormat:@"%f",coordinate.latitude];

    

    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];

    

    if (_sendPointBlock) {

        _sendPointBlock(_latitude,_longitude);

    }

    

//    [[iToast makeText:@"正在定位....."] show];

    //31.20476569,+121.62868477

//    [self getAddressByLatitude:coordinate.longitude longitude:coordinate.latitude];

    //如果不需要实时定位,使用完即使关闭定位服务

   [_locationManager stopUpdatingLocation];

}

#pragma mark 根据地名确定地理坐标

- (void)getCoordinateByAddress:(NSString *)address{

    //地理编码

    [_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {

        //取得第一个地标,地标中存储了详细的地址信息,注意:一个地名可能搜索出多个地址

//        CLPlacemark *placemark=[placemarks firstObject];

//        

//        CLLocation *location=placemark.location;//位置

//        CLRegion *region=placemark.region;//区域

//        NSDictionary *addressDic= placemark.addressDictionary;//详细地址信息字典,包含以下部分信息

        //NSString *name=placemark.name;//地名

        //NSString *thoroughfare=placemark.thoroughfare;//街道

        //NSString *subThoroughfare=placemark.subThoroughfare; //街道相关信息,例如门牌等

        //NSString *locality=placemark.locality; // 城市

        //NSString *subLocality=placemark.subLocality; // 城市相关信息,例如标志性建筑

        //NSString *administrativeArea=placemark.administrativeArea; // 州

        //NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息

        //NSString *postalCode=placemark.postalCode; //邮编

        //NSString *ISOcountryCode=placemark.ISOcountryCode; //国家编码

        //NSString *country=placemark.country; //国家

        //NSString *inlandWater=placemark.inlandWater; //水源、湖泊

        //NSString *ocean=placemark.ocean; // 海洋

        //NSArray *areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标

        //NSLog(@"位置:%@,区域:%@,详细信息:%@",location,region,addressDic);

    }];

}

#pragma mark 根据坐标取得地名

-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude {

    //反地理编码

    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

    

    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {

        CLPlacemark *placemark = [placemarks firstObject];

        _name         = placemark.name;//名称

        _locality     = placemark.locality;//城市名

        _area         = placemark.subLocality;//区

        _thoroughfare = placemark.thoroughfare;//街道

        dispatch_async(dispatch_get_main_queue(), ^{

            if (_addressBlock) {

                _addressBlock(_locality,_area);

            }

            

        });

//        [[iToast makeText:_name] show];

//        [[iToast makeText:_locality] show];

//        [[iToast makeText:[NSString stringWithFormat:@"%@",error]] show] ;

        

    }];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: