iOS 使用CoreLocation获取当前所在城市 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    在之前的一篇博客-CoreLocation — iOS中的位置信息中, 简单描述了CoreLocation的使用, 并获取经纬度信息. 接下来, 将要从地理位置信息中反向解析出当前所在城市等信息.

    首先, 初始化CLLocationManager对象, 设置delegate,

    然后startUpdatingLocation即开始定位.

    注意: 要继承CLLocationManagerDelegate协议.

<code class="hljs" bjectivec="">@property(strong, nonatomic) CLLocationManager *locationManager;#pragma mark - 获取当前定位城市- (void)locate {  self.currentCity = [[NSString alloc] init];  // 判断是否开启定位  if ([CLLocationManager locationServicesEnabled]) {    self.locationManager = [[CLLocationManager alloc] init];    self.locationManager.delegate = self;    [self.locationManager startUpdatingLocation];  } else {    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@home_cannot_locate, comment:@无法进行定位) message:NSLocalizedString(@home_cannot_locate_message, comment:@请检查您的设备是否开启定位功能) delegate:self cancelButtonTitle:NSLocalizedString(@common_confirm,comment:@确定) otherButtonTitles:nil, nil];    [alert show];  }}</code>

    然后, 实现didUpdateLocations方法, 并在其中解析出城市信息.

<code class="hljs" bjectivec="">#pragma mark - CoreLocation Delegate- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {  CLLocation *currentLocation = [locations lastObject]; // 最后一个值为最新位置  CLGeocoder *geoCoder = [[CLGeocoder alloc] init];  // 根据经纬度反向得出位置城市信息  [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {    if (placemarks.count > 0) {      CLPlacemark *placeMark = placemarks[0];      self.currentCity = placeMark.locality;      // ? placeMark.locality : placeMark.administrativeArea;      if (!self.currentCity) {        self.currentCity = NSLocalizedString(@home_cannot_locate_city, comment:@无法定位当前城市);      }// 获取城市信息后, 异步更新界面信息.      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        dispatch_async(dispatch_get_main_queue(), ^{          self.cityDict[@*] = @[self.currentCity];          [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];        });      });    } else if (error == nil && placemarks.count == 0) {      NSLog(@No location and error returned);    } else if (error) {      NSLog(@Location error: %@, error);    }  }];  [manager stopUpdatingLocation];}</code>

    结果如图:

无法定位定位成功

最新文章