iOS开发定位权限
2021-06-18 本文已影响0人
铁头娃_e245
定位权限
如果项目需要开启定位功能,需要在info.plist中设置Privacy - Location Always and When In Use Usage Description
和Privacy - Location When In Use Usage Description
。
在需要开启定位权限的地方去弹起授权弹窗
需要设置CLLocationManager
属性 (这里是个大坑,必须是属性,如果用局部变量弹不起来弹窗
)
@property (nonatomic, strong) CLLocationManager *locationManager;
设置代理及代理方法(可选,非必须设置,开启持续定位才会触发回调,弹窗授权后不触发)
<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
NSLog(@"更新位置的回调");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"错误信息回调");
}
调起定位弹窗
- (void)GetLocationPermissionVerifcationWithController{
BOOL enable = [CLLocationManager locationServicesEnabled];
NSInteger state = [CLLocationManager authorizationStatus];
if (!enable || 2 > state) {// 尚未授权位置权限
if (8 <= [[UIDevice currentDevice].systemVersion floatValue]) {
NSLog(@"系统位置权限授权弹窗");
// 系统位置权限授权弹窗
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager requestAlwaysAuthorization];
[self.locationManager requestWhenInUseAuthorization];
}
}
}
已授权判断
BOOL enable = [CLLocationManager locationServicesEnabled];
CLAuthorizationStatus state = [CLLocationManager authorizationStatus];
if (enable && (state == kCLAuthorizationStatusAuthorizedAlways || state == kCLAuthorizationStatusAuthorizedWhenInUse)) {// 已授权位置权限
}