您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 定位實戰:CLLocationManager 用法與地理編碼反查城市

編輯:iOS 開發綜合

前陣子在專案中遇到定位(CLLocation)的需求,踩過幾個坑之後整理成這篇筆記,把重點與容易忽略的設定一次記錄下來。

一、CLLocationManager 常用操作

// 開始定位:呼叫後會持續更新位置,並頻繁回呼代理方法
- (void)startUpdatingLocation;
// 停止定位
- (void)stopUpdatingLocation;

// 位置更新時的回呼
- (void)locationManager:(CLLocationManager *)manager
        didUpdateLocations:(NSArray *)locations;

// 距離篩選器:位置變化超過多少公尺才回呼
@property (assign, nonatomic) CLLocationDistance distanceFilter;
// 定位精確度:越精準越耗電
@property (assign, nonatomic) CLLocationAccuracy desiredAccuracy;

二、使用前必做的三件事

  1. 匯入 CoreLocation 框架。
  2. 讓類別遵守 CLLocationManagerDelegate 協議。
  3. 建立 CLLocationManager 實例並設定代理。

還有一個很多人忽略的關鍵:從 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 不會再跳出提示,必須引導使用者到「設定」開啟。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved