苹果已经强制开发者在请求定位服务时获得用户的授权,此外iOS状态栏中还有指示图标,提示用户当前应用是否正在使用定位服务。还支持让应用开发者调用全新的“访问监控”功能,当用户允许后应用才能获得更多的定位数据。
1、引入CoreLocation.framework
使用#import <CoreLocation/CoreLocation.h>
2、初始化CLLocationManager并开始定位
self.locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest; 最佳精确
_locationManager.distanceFilter = 10; 10米更新
[_locationManager startUpdatingLocation];
3、实现CLLocationManagerDelegate的代理方法
(1)获取到位置数据,返回的是一个CLLocation的数组,一般使用其中的一个
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{ CLLocation *currLocation = [locations lastObject];
NSLog(@"经度=%f 纬度=%f 高度=%f",
currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
}
(2)获取用户位置数据失败的回调方法,在此通知用户
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{ if ([error code] == kCLErrorDenied)
{ //访问被拒绝 }
if ([error code] == kCLErrorLocationUnknown) { //无法获取位置信息 }
}
4、在
viewWillDisappear
关闭定位
- (void)viewWillDisappear:(BOOL)animated
{ [super viewWillDisappear:animated];
[_locationManager stopUpdatingLocation];
}
定位授权的方法
1)始终允许访问位置信息
- (void)requestAlwaysAuthorization;
(2)使用应用程序期间允许访问位置数据
- (void)requestWhenInUseAuthorization;
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10;
[_locationManager requestAlwaysAuthorization];//添加这句[_locationManager startUpdatingLocation];
2、在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription
这两个键的值就是授权alert的描述,示例配置如下[勾选Show Raw Keys/Values后进行添加
]:
![ios8_location_alert.png](https://i-blog.csdnimg.cn/blog_migrate/97ee353ddf1194e4bb548f242e6ba660.png)