CLLocationManager无法定位问题,CLLocationManagerDelegate不调用didUpdateLocations

      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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值