在iOS8中,苹果已经强制开发者在请求定位服务时获得用户的授权,此外iOS状态栏中还有指示图标,提示用户当前应用是否正在使用定位服务。另外在iOS8中,苹果进一步改善了定位服务,让开发者请求定位服务时需要向用户提供更多的透明。此外,iOS8中还支持让应用开发者调用全新的“访问监控”功能,当用户允许后应用才能获得更多的定位数据。
iOS8以前使用CoreLocation定位
1、首先定义一个全局的变量用来记录CLLocationManager对象,引入CoreLocation.framework
使用#import
1 @property (nonatomic, strong) CLLocationManager *locationManager;
2、初始化CLLocationManager并开始定位
1 self.locationManager = [[CLLocationManager alloc]init]; 2 _locationManager.delegate = self; 3 _locationManager.desiredAccuracy = kCLLocationAccuracyBest; _locationManager.distanceFilter = 10; 4 [_locationManager startUpdatingLocation];
3、实现CLLocationManagerDelegate的代理方法
(1)获取到位置数据,返回的是一个CLLocation的数组,一般使用其中的一个
1 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 2 { 3 CLLocation *currLocation = [locations lastObject]; 4 NSLog(@经度=%f 纬度=%f 高度=%f, currLocation.coordinrdinate.longitude, currLocation.altitude); 5 }
(2)获取用户位置数据失败的回调方法,在此通知用户
1 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 2 { if ([error code] == kCLErrorDenied) 3 { //访问被拒绝 } 4 if ([error code] == kCLErrorLocationUnknown) 5 { //无法获取位置信息 6 } 7 }
4、在viewWillDisappear
关闭定位
1 - (void)viewWillDisappear:(BOOL)animated{ 2 [super viewWillDisappear:animated]; 3 [_locationManager stopUpdatingLocation]; 4 }
iOS8中使用CoreLocation定位
1、在使用CoreLocation前需要调用如下函数【iOS8专用】:
iOS8对定位进行了一些修改,其中包括定位授权的方法,CLLocationManager增加了下面的两个方法:
(1)始终允许访问位置信息
- (void)requestAlwaysAuthorization;
(2)使用应用程序期间允许访问位置数据
- (void)requestWhenInUseAuthorization;
示例如下:
1 self.locationManager = [[CLLocationManager alloc]init]; 2 _locationManager.delegate = self; 3 _locationManager.desiredAccuracy = kCLLocationAccuracyBest;//精确度最好 4 _locationManager.distanceFilter = 10;//每移动10米刷新一次 5 [_locationManager requestAlwaysAuthorization]; 6 //添加这句[_locationManager startUpdatingLocation];
当然你也可以让locatonManager成为懒加载对象;不是总是手动申请授权,而是判断设备高于iOS8之后才申请
示例如下:
懒加载:
1 - (CLLocationManager *)locationManager 2 { 3 if (!_locationManager) { 4 self.locationManager = [[CLLocationManager alloc] init]; 5 } 6 return _locationManager; 7 }
ios8以上设备申请授权:
1 if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) { 2 [self.locationManager requestWhenInUseAuthorization];//我不喜欢那些乱七八糟的设置,申请就只做申请,其他的其他地方设置 3 }
(实现代码不唯一,没个人的代码洗好都不同,问题解决最重要)
2、在Info.plist文件中添加如下string类型配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription
这两个键的值就是授权alert的描述,示例配置如下[勾选Show Raw Keys/Values后进行添加
]: