以下示範如何透過 CoreLocation 定位取得目前所在的城市名稱。
1. 導入頭檔:
#import <CoreLocation/CoreLocation.h>
2. 實作 CLLocationManagerDelegate 協定。
3. 定義定位屬性:
@property(nonatomic,retain) CLLocationManager *locationManager;
4. 開始定位:
- (void)locate
{
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
} else {
// 提示使用者無法進行定位
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位不成功,請確認開啟定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
[alertView show];
}
[self.locationManager startUpdatingLocation];
}
5. 實作代理回呼方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// locations 存儲持續更新的座標,取最後一個為最新位置
CLLocation *currentLocation = [locations lastObject];
// 以 CLGeocoder 反向地理編碼取得城市
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) {
if (array.count > 0) {
CLPlacemark *placemark = [array objectAtIndex:0];
NSString *city = placemark.locality;
if (!city) {
// 直轄市無法透過 locality 取得,需改用 administrativeArea
city = placemark.administrativeArea;
}
self.cityName = city;
}
}];
// 只需取得一次經緯度,取得後停止更新
[manager stopUpdatingLocation];
}
特別注意:四大直轄市的城市資訊無法透過 locality 取得,只能改用 administrativeArea(若 city 為空即代表是直轄市)。