前陣子在專案中遇到定位(CLLocation)的需求,踩過幾個坑之後整理成這篇筆記,把重點與容易忽略的設定一次記錄下來。
// 開始定位:呼叫後會持續更新位置,並頻繁回呼代理方法
- (void)startUpdatingLocation;
// 停止定位
- (void)stopUpdatingLocation;
// 位置更新時的回呼
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations;
// 距離篩選器:位置變化超過多少公尺才回呼
@property (assign, nonatomic) CLLocationDistance distanceFilter;
// 定位精確度:越精準越耗電
@property (assign, nonatomic) CLLocationAccuracy desiredAccuracy;
CLLocationManagerDelegate 協議。還有一個很多人忽略的關鍵:從 iOS 8 開始,必須在 Info.plist 中加入 NSLocationWhenInUseUsageDescription 與 NSLocationAlwaysUsageDescription 這兩個 NSString 型別的欄位,否則定位不會啟動,且不會有任何明顯錯誤。前者對應「使用 App 期間允許定位」,後者對應「永遠允許」。請依實際情境填入描述文字,這些文字會直接顯示在系統的權限提示中。
// 啟動定位
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled] == NO) {
// 使用者或裝置關閉了定位服務
}
_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
_locationManager.distanceFilter = kCLDistanceFilterNone; // 每次變化都回呼
[_locationManager requestWhenInUseAuthorization]; // 僅前台定位
[_locationManager startUpdatingLocation];
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation *last = locations.lastObject;
// 經度與緯度
CGFloat longTI = last.coordinate.longitude;
CGFloat latTI = last.coordinate.latitude;
_longitudeLabel.text = [NSString stringWithFormat:@"%f", longTI];
_latitudeLabel.text = [NSString stringWithFormat:@"%f", latTI];
// 以經緯度反向地理編碼,取得地址資訊
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:last completionHandler:^(NSArray *array, NSError *error) {
if (array.count > 0) {
CLPlacemark *placemark = array.firstObject;
// 取城市名稱
NSString *city = placemark.locality;
if (!city) {
// 直轄市的 locality 可能為空,此時改用省份欄位
city = placemark.administrativeArea;
}
_cityName = city;
} else if (error != nil) {
NSLog(@"反向地理編碼失敗 = %@", error);
}
}];
// 只需要一次座標即可停止更新,避免持續耗電
[manager stopUpdatingLocation];
}
locations 是陣列,最新一筆永遠在 lastObject,不要拿第 0 個。locality,回退到 administrativeArea 是實務上常見的處理方式。stopUpdatingLocation;持續定位會明顯增加耗電,也容易引起使用者反感。stopUpdatingLocation,例如 viewDidDisappear 或進入背景時。requestWhenInUseAuthorization 不會再跳出提示,必須引導使用者到「設定」開啟。