ios中关于系统定位CLLocationManager的使用解析
//1、添加定位管理委托协议 CLLocationManagerDelegate
//2、初始化定位管理对象
self.locationManager=[[CLLocationManager alloc]init];
self.locationManager.delegate=self;
//定位精度
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//多长距离更新一次位置
self.locationManager.distanceFilter=50;
if (UIDevice.currentDevice.systemVersion.integerValue>8.0)
{
[self.locationManager requestAlwaysAuthorization];
[self.locationManager requestWhenInUseAuthorization];
}
//开启定位服务
if (self.locationManager.locationServicesEnabled) {
[self.locationManager startUpdatingLocation];
}
//3、调用系统定位方法
#pragma mark - CLLocation Delegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status)
{
case kCLAuthorizationStatusNotDetermined:
if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[_locationManager requestAlwaysAuthorization];
}
break;
default:
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//获取当前位置信息
CLLocation *location = [locations objectAtIndex:0];
//判断是否是在国内
if (![WGS84TOGCJ02 isLocationOutOfChina:[location coordinate]])
{
//设置锁,防止并发写入
[[NSUserDefaults standardUserDefaults] synchronize];
//转换后的coord
CLLocationCoordinate2D coord = [WGS84TOGCJ02 transformFromWGSToGCJ:[location coordinate]];
_myCoordinate = coord;
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",_myCoordinate.latitude] forKey:KCurrentLat];
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",_myCoordinate.longitude] forKey:KCurrentLng];
}
//创建反地理编码对象
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//将经纬度信息转换成字符串位置信息
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error)
{
// NSLog(@"placemark:%@",array);
if (array.count > 0)
{
CLPlacemark *placemark = [array objectAtIndex:0];
if (![DGFunction xfunc_check_strEmpty:placemark.locality])
{
[[ NSUserDefaults standardUserDefaults] setObject:placemark.locality forKey:@"localCity"];
[[NSUserDefaults standardUserDefaults] synchronize];
// NSDictionary *dic = @{@"city":placemark.locality};
if (![DGFunction xfunc_check_strEmpty:placemark.locality]) {
[[NSUserDefaults standardUserDefaults] setObject:placemark.administrativeArea forKey:k_Current_Province];
}
if (![DGFunction xfunc_check_strEmpty:placemark.locality]) {
[[NSUserDefaults standardUserDefaults] setObject:placemark.locality forKey:k_Current_City];
}
if (![DGFunction xfunc_check_strEmpty:placemark.subLocality]) {
[[NSUserDefaults standardUserDefaults] setObject:placemark.subLocality forKey:k_Current_Area];
}
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"locality:%@ subLocality:%@",placemark.locality,placemark.subLocality);
//关闭定位服务
[_locationManager stopUpdatingLocation];
}
}
}];
}