很多 App 上線時都需要知道使用者目前在哪個城市。雖然各家地圖 SDK 都有這個能力,但若不希望引入第三方相依,用 iOS 自帶的 CoreLocation 就足夠了。以下示範取得經緯度,再透過反向地理編碼換算成城市、行政區與街道。
以下程式碼以 iOS 7 的寫法為主,文末再補充 iOS 8 之後必須多做的兩件事。
先在專案的 Build Phases 中加入 CoreLocation.framework,然後在控制器引入頭檔:
#import <CoreLocation/CoreLocation.h>
@interface TYViewController () <CLLocationManagerDelegate> {
CLLocationManager *_locationManager;
}
@end
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// 經緯度顯示
self.longitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];
self.latitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];
// 反向地理編碼:由座標推回地址
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error) {
if (array.count > 0) {
CLPlacemark *placemark = [array objectAtIndex:0];
self.location.text = placemark.name;
NSString *city = placemark.locality;
if (!city) {
// 直轄市的 city 通常拿不到,需退回 administrativeArea
city = placemark.administrativeArea;
}
NSLog(@"city = %@", city);
_cityLable.text = city;
[_cityButton setTitle:city forState:UIControlStateNormal];
}
else if (error == nil && [array count] == 0) {
NSLog(@"No results were returned.");
}
else if (error != nil) {
NSLog(@"An error occurred = %@", error);
}
}];
// 只需要一次座標,取到就停止更新,省電
[manager stopUpdatingLocation];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self initializeLocationService];
}
- (void)initializeLocationService {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 精度到公尺
_locationManager.distanceFilter = kCLDistanceFilterNone; // 不做距離過濾
[_locationManager startUpdatingLocation];
}
執行後,在模擬器中手動設定一組座標(或直接用真機),即可取得對應的城市名稱。
CLPlacemark 封裝了大量地理資訊屬性,從國家到街道、郵遞區號都有,可依需求取用。若街道顯示為英文,記得先處理本地化,並把模擬器語言切換為中文。
1. 在 Info.plist 加入用途說明字串。新增 NSLocationAlwaysUsageDescription 與 NSLocationWhenInUseUsageDescription,型別皆為 String,值可自訂(不填則可能導致定位時直接拿到空值或系統不彈窗)。這段文字會顯示在系統詢問使用者是否允許定位的提示中,寫清楚「為什麼需要位置」能明显提高同意率。
2. 啟動定位前先請求授權。在原本的初始化方法中補一行:
- (void)initializeLocationService {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = kCLDistanceFilterNone;
// iOS 8 以上需要主動請求授權,依使用情境二選一:
// requestAlwaysAuthorization —— 隨時可取得位置
// requestWhenInUseAuthorization —— 僅 App 使用期間可取得
[_locationManager requestWhenInUseAuthorization];
[_locationManager startUpdatingLocation];
}
反向地理編碼會走網路,因此請務必實作錯誤與空值的處理,別假設 callback 一定有資料。定位精度 kCLLocationAccuracyBest 最耗電,若只需判斷城市,改用 kCLLocationAccuracyThreeKilometers 就夠了。另外 iOS 後續版本已把 didUpdateToLocation:fromLocation: 標記為廢棄,新專案請改用 locationManager:didUpdateLocations:,並記得在 didFailWithError: 中處理使用者拒絕授權或 GPS 訊號弱的情況。