在Info.plist文件中添加如下配置:
//始终允许访问位置信息
(1)NSLocationAlwaysUsageDescription
//使用应用程序期间允许访问位置数据
(2)NSLocationWhenInUseUsageDescription
//创建一个管理者
- (CLLocationManager *)manager
{
if (!_manager) {
_manager = [[CLLocationManager alloc] init];
_manager.delegate = self;
// 授权使应用在前台后台都能使用定位服务
[_manager requestAlwaysAuthorization];
// _manager.desiredAccuracy = kCLLocationAccuracyBest;
// _manager.distanceFilter = 10;
}
return _manager;
}
//然后调用startUpdatingLocation方法
[self.manager startUpdatingLocation];
实现CLLocationManagerDelegate的代理方法
(1)获取到位置数据,返回的是一个CLLocation的数组,一般使用其中的一个
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *location = [locations firstObject];
NSLog(@"%f %f",location.coordinate.longitude,location.coordinate.latitude);
}
(2)获取用户位置数据失败的回调方法,在此通知用户
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{ if ([error code] == kCLErrorDenied)
{ //访问被拒绝
}
if ([error code] == kCLErrorLocationUnknown)
{ //无法获取位置信息
}
}
//反地理编码
//先懒加载CLGeocoder对象
- (CLGeocoder *)geoCoder
{
if (!_geoCoder) {
_geoCoder = [[CLGeocoder alloc] init];
}
return _geoCoder;
}
//完成定位后会调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { self.location = [locations firstObject]; //开始反地理编码 [self.geoCoder reverseGeocodeLocation:self.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { CLPlacemark *placemark = [placemarks firstObject]; self.placemark = placemark; }]; }