最近在ios8.0使用CLLocationManager定位服務,發現老不能定位,查看設置菜單中的項也是處於未知狀態.想起之前都有一個彈出框提示用戶是否允許定位,這次一直沒有出現了.原來ios8.0下的定位服務需要申請授權了. 具體代碼如下:
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗電量越大。
_locationManager.distanceFilter = 100; //控制定位服務更新頻率。單位是“米”
[_locationManager startUpdatingLocation];
//在ios 8.0下要授權
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[_locationManager requestWhenInUseAuthorization]; //調用了這句,就會彈出允許框了.
}
注意:
在Info.plist文件還要加上NSLocationWhenInUseUsageDescription這個key,Value可以爲空,
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation * currLocation = [locations lastObject];
NSLog(@"%@",[NSString stringWithFormat:@"%.3f",currLocation.coordinate.latitude]);
NSLog(@"%@",[NSString stringWithFormat:@"%.3f",currLocation.coordinate.longitude]);
}