在之前的一篇博客-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];
}
結果如圖: