CLLocationManager正确使用
1. 代码片段
<pre name="code" class="objc">#import <MapKit/MapKit.h>
@interface BiLocationEngine()<CLLocationManagerDelegate>
@property (nonatomic, retain) CLLocationManager * locationManager;
@property (nonatomic, retain) CLGeocoder * geocoder;
@end
@implementation BiLocationEngine
SINGLE_INSTANCE_IMPLEMENTION(BiLocationEngine)
- (void)startLocation {
if (nil == self.locationManager) {
self.locationManager = [[CLLocationManager alloc] init];//创建位置管理器
self.locationManager.delegate = self; //设置代理
// self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; //指定需要的精度级别
}
if ([CLLocationManager locationServicesEnabled]) {
[self.locationManager requestWhenInUseAuthorization]; //iOS8 需要添加这句
[self.locationManager startUpdatingLocation];
}
else
{ // 告诉用户打开定位服务
}
}
- (void)onGetLocation:(CLLocation *)location {
if (self.geocoder == nil) {
self.geocoder = [[CLGeocoder alloc] init];
}
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"address City %@", [placemark.addressDictionary objectForKey:@"City"]);
NSString * cityName = [placemark.addressDictionary objectForKey:@"City"];
}
else if (error == nil && [placemarks count] == 0){
NSLog(@"No results were returned.");
}
else if (error != nil) {
NSLog(@"An error occurred = %@", error);
}
}];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
[self.locationManager stopUpdatingLocation];
// 2.然后,取出第一个位置,根据其经纬度,通过CLGeocoder反向解析,获得该位置所在的城市名称,转成城市对象,用工具保存
CLLocation *loc = locations[0];
[self onGetLocation:loc];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error code] == kCLErrorDenied) {
//访问被拒绝
}
if ([error code] == kCLErrorLocationUnknown) {
//无法获取位置信息
}
}
@end
2. Info.plist设置
注意看这句话:如果Info.plist中没有NSLocationWhenInUseUsageDescription这个key,requestWhenInUseAuthorization()这个方法将会do nothing(不会做任何事)。就是说调了这个方法也是白调。
在Info.plist中加上NSLocationWhenInUseUsageDescription这个key,并设置上值,如下图所示:
这里就设置完成了,否则不会弹出是否开启定位隐私时的对话框,也即不能开始定位。至此,就能开始定位了。over