天氣、地圖、打卡、外送……越來越多 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 以節省電力。