iOS - 使用CoreLocation擷取當前所在城市

來源:互聯網
上載者:User

iOS - 使用CoreLocation擷取當前所在城市

在之前的一篇部落格-CoreLocation — iOS中的位置資訊中, 簡單描述了CoreLocation的使用, 並擷取經緯度資訊. 接下來, 將要從地理位置資訊中反向解析出當前所在城市等資訊.
首先, 初始化CLLocationManager對象, 設定delegate,
然後startUpdatingLocation即開始定位.
注意: 要繼承CLLocationManagerDelegate協議.

@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];  }}

然後, 實現didUpdateLocations方法, 並在其中解析出城市資訊.

#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];}

結果:

無法定位 定位成功

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.