在特定场景下我们需要判断用户是否允许应用获取定位权限
1.导入类库:
#import <CoreLocation/CLLocationManager.h>
2.判断用户手机是否开启了定位服务:
这里就要查看CLLocationManager的授权状态,此方法会返回当前授权状态:
[CLLocationManager authorizationStatus]
授权状态为枚举值:
kCLAuthorizationStatusNotDetermined //用户尚未对该应用程序作出选择
kCLAuthorizationStatusRestricted //应用程序的定位权限被限制
kCLAuthorizationStatusAuthorizedAlways //一直允许获取定位
kCLAuthorizationStatusAuthorizedWhenInUse //在使用时允许获取定位
kCLAuthorizationStatusAuthorized //已废弃,相当于一直允许获取定位
kCLAuthorizationStatusDenied //拒绝获取定位
3.判断用户是否授权应用获取定位权限的完整代码:
if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
//定位功能可用
}else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
//定位不能用
}
有不足之处还望补充。
网友评论
//如果没给权限:显示提醒
if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
//定位功能可用
shareLocationUploadManager = [DRuploaddataAndLocationManager shareManager];
}else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
//定位不能用
[self showAlertWithTitle:@"请求打开定位权限" Message:@"" CancelTitle:@"不定位" OthersTitles:@[@"定位"] ConfirmHandel:^(NSInteger index) {
if (index==1) {
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
}];
}else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
[self showAlertWithTitle:@"请求定位权限" Message:@"" CancelTitle:@"取消" OthersTitles:@[@"确定"] ConfirmHandel:^(NSInteger index) {
if (index==1) {
shareLocationUploadManager = [DRuploaddataAndLocationManager shareManager];
}else{
}
}];
}