在iOS8中,苹果已经强制开发者在请求定位服务时得到用户的受权,此外iOS状态栏中还有指示图标,提示用户当前应用是否正在使用定位服务。另外在iOS8中,苹果进一步改善了定位服务,让开发者请求定位服务时须要向用户提供更多的透明。此外,iOS8中还支持让应用开发者调用全新的“访问监控”功能,当用户容许后应用才能得到更多的定位数据。ios
一、首先定义一个全局的变量用来记录CLLocationManager对象,引入CoreLocation.framework
使用#import
git
1 @property (nonatomic, strong) CLLocationManager *locationManager;
二、初始化CLLocationManager并开始定位数组
1 self.locationManager = [[CLLocationManager alloc]init]; 2 _locationManager.delegate = self; 3 _locationManager.desiredAccuracy = kCLLocationAccuracyBest; _locationManager.distanceFilter = 10; 4 [_locationManager startUpdatingLocation];
三、实现CLLocationManagerDelegate的代理方法app
(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)获取用户位置数据失败的回调方法,在此通知用户atom
1 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 2 { if ([error code] == kCLErrorDenied) 3 { //访问被拒绝 } 4 if ([error code] == kCLErrorLocationUnknown) 5 { //没法获取位置信息 6 } 7 }
四、在viewWillDisappear
关闭定位spa
1 - (void)viewWillDisappear:(BOOL)animated{ 2 [super viewWillDisappear:animated]; 3 [_locationManager stopUpdatingLocation]; 4 }
一、在使用CoreLocation前须要调用以下函数【iOS8专用】:代理
iOS8对定位进行了一些修改,其中包括定位受权的方法,CLLocationManager增长了下面的两个方法:code
(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 }
(实现代码不惟一,没我的的代码洗好都不一样,问题解决最重要)
二、在Info.plist文件中添加以下string类型配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription
这两个键的值就是受权alert的描述,示例配置以下[勾选Show Raw Keys/Values后进行添加
]: