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

iOS 定位實戰:取得使用者目前所在城市

編輯:iOS 開發綜合

透過 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. 實作定位回呼

#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,並建立一份例外清單來處理。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved