您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 定位實作:取得當前地理位置的步驟解析

編輯:iOS 相關資訊

天氣、地圖、打卡、外送……越來越多 App 需要知道使用者身在何處。在 iOS 中,取得當前地理位置靠的是 Core Location 框架。本文把整個流程拆成幾個清楚的步驟,讓你快速上手定位功能。

前置準備

首先導入 Core Location 框架:

#import <CoreLocation/CoreLocation.h>

然後讓你的類採用 CLLocationManagerDelegate 協議,並準備好相關變數:

@interface SomeViewController () <CLLocationManagerDelegate>
{
    // locationManager 用於取得位置,checkinLocation 用於保存取得的位置資訊
    NSString *currentLatitude;
    NSString *currentLongitude;
    CLLocationManager *locManager;
    CLLocation *checkinLocation;
}
@end

步驟一:實作位置更新的代理方法

當程式執行到這個方法時,locationManager 已經取得了目前位置,因此要在這裡把位置存進變數:

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    checkinLocation = newLocation;
    // 可在此做其他處理
}

步驟二:啟動定位服務

上面那個代理方法,其實是被 startUpdatingLocation 觸發的。也就是說,當程式執行到 startUpdatingLocation 時,位置更新方法就會被呼叫:

- (void)setupLocationManager {
    locationManager = [[CLLocationManager alloc] init];
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"Starting CLLocationManager");
        locationManager.delegate = self;
        locationManager.distanceFilter = 200;               // 移動超過 200 公尺才更新
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;  // 最佳精度
        [locationManager startUpdatingLocation];
    } else {
        NSLog(@"Cannot Starting CLLocationManager");
    }
}

流程串起來

整體流程是:先配置並啟動 CLLocationManager(設定代理、精度與更新距離),呼叫 startUpdatingLocation 後,系統便會持續回呼 didUpdateToLocation:fromLocation:,你就能在裡面取得最新的經緯度座標。實作時別忘了在 Info.plist 中加上定位用途說明(如 NSLocationWhenInUseUsageDescription),並在使用定位後視情況呼叫 stopUpdatingLocation 以節省電力。

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