CLLocationManager属性
- locationServicesEnabled 当前定位服务是否可用
BOOL enable = [CLLocationManager locationServicesEnabled];
deferredLocationUpdatesAvailable 延迟定位更新是否可用
significantLocationChangeMonitoringAvailable 大位置改变监听是否可用
headingAvailable 是否支持磁力计计算方向
desiredAccuracy 定位精度要求
//kCLLocationAccuracyBest; 精度要求最高
//kCLLocationAccuracyNearestTenMeters; 10米
//kCLLocationAccuracyHundredMeters; 百米
//kCLLocationAccuracyKilometer; 千米
//kCLLocationAccuracyThreeKilometers; 3千米
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
- distanceFilter 距离筛选器,表示设备至少移动n米,才通知委托更新
_locationManager.distanceFilter = 5;
- pausesLocationUpdatesAutomatically 设置iOS设备是否可暂停定位来节省电池的电量。如果该属性设为“YES”,则当iOS设备不再需要定位数据时,iOS设备可以自动暂停定位。
_locationManager.pausesLocationUpdatesAutomatically = NO;
- activityType:设置定位数据的用途
//CLActivityTypeOther 定位数据作为普通用途
//CLActivityTypeAutomotiveNavigation定位数据作为车辆导航使用
//CLActivityTypeFitness 定位数据作为步行导航使用
//CLActivityTypeOtherNavigation定位数据作为其他导航
[_locationManager setActivityType:CLActivityTypeFitness];
- allowsBackgroundLocationUpdates ios9以上 是否允许后台更新定位 同时:target-Capabilities-Background Modes-location updates打钩
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)
{
_locationManager.allowsBackgroundLocationUpdates = YES;
}
- 授权定位 ios8.0以上可用 此外需要在plist文件配置
ios 10
Privacy - Location Always Usage Description
Privacy - Location Usage Description
ios 8.0-9.0
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
//requestAlwaysAuthorization 总是获取位置
//requestWhenInUseAuthorization 使用期间
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
//使用期间
[locationManager requestAlwaysAuthorization];
}
简单的示列
-(CLLocationManager *) locationManager
{
if (_locationManager == nil)
{
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = 5; //5米更新一次
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.pausesLocationUpdatesAutomatically = NO;
[_locationManager setActivityType:CLActivityTypeFitness];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)
{
_locationManager.allowsBackgroundLocationUpdates = YES;
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
//使用期间
[_locationManager requestAlwaysAuthorization];
}
}
return locationManager;
}
CLLocationManagerDelegate
app在前台时,会调用mapView的代理方法。
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
但是想要获取到app进入后台时的位置信息,需要用到这个方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
需要注意的是,locationManager的坐标是不能直接用在mapView上,位置信息大概会偏一条街。。所以我们需要将世界标准坐标转成火星坐标,方可在mapView上正常显示~