透過 CoreLocation 取得使用者所在城市,大致可以拆成五個步驟。
#import <CoreLocation/CoreLocation.h>
讓你的類別遵守 CLLocationManagerDelegate。
@property (nonatomic, retain) CLLocationManager *locationManager;
- (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];
}#pragma mark - CoreLocation Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// locations 保存了持續更新的座標,取最後一筆為最新位置。
// 若不想持續更新,取得一筆後即可 stopUpdatingLocation
CLLocation *currentLocation = [locations lastObject];
// 以經緯度做反向地理編碼,取得地址資訊
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) {
if (array.count > 0) {
CLPlacemark *placemark = [array objectAtIndex:0];
NSLog(@"%@", placemark.name);
// 取得城市名稱
NSString *city = placemark.locality;
if (!city) {
// 直轄市無法從 locality 取得,需改抓行政區(若 city 為空即可判定是直轄市)
city = placemark.administrativeArea;
}
self.cityName = city;
} else if (error == nil && [array count] == 0) {
NSLog(@"No results were returned.");
} else if (error != nil) {
NSLog(@"An error occurred = %@", error);
}
}];
// 系統會持續更新直到你叫停;這裡只需要一筆座標,取完即停止
[manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if (error.code == kCLErrorDenied) {
// 使用者拒絕定位。可按住 Option 點擊 kCLErrorDenied 查看說明,
// 或直接印出 error.code 追查出錯原因
}
}權限請求。iOS 8 之後,光呼叫 startUpdatingLocation 是不夠的,必須先明確請求權限:只需要「使用 App 期間」可用 requestWhenInUseAuthorization,需要背景定位則用 requestAlwaysAuthorization,並在 Info.plist 中補上對應的 NSLocationWhenInUseUsageDescription 說明文字,否則 App 會直接崩潰。
城市判斷的邏輯。範例中用 locality 為空來推測是直轄市,這是個實用但並非百分之百嚴謹的做法,某些國外地區的行政區劃分也可能讓 locality 回傳 nil。若對準確度要求高,建議同時比對 administrativeArea 與 country,並建立一份例外清單來處理。