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];}
結果: