CoreLocation 框架讓 iOS 應用輕鬆獲取裝置地理位置 (經緯度、海拔、速度、航向)。本文以「Utility Application」範本為基礎,完整演示從專案建立、框架引入、程式碼實作、介面佈置到實機測試的全流程。
WhereAmI+ → 搜尋並加入 CoreLocation.framework
#import
#import
@interface MainView : UIView {
IBOutlet UITextField *altitude;
IBOutlet UITextField *latitude;
IBOutlet UITextField *longitude;
CLLocationManager *locManager;
BOOL wasFound;
}
- (IBAction)update;
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error;
@end
#import "MainView.h"
@implementation MainView
- (IBAction)update {
locManager = [[CLLocationManager alloc] init];
locManager.delegate = self;
locManager.desiredAccuracy = kCLLocationAccuracyBest; // 最高精度
[locManager startUpdatingLocation];
}
- (void)awakeFromNib {
[self update]; // 介面載入即啟動定位
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
if (wasFound) return; // 僅取首次定位成功
wasFound = YES;
CLLocationCoordinate2D coord = newLocation.coordinate;
latitude.text = [NSString stringWithFormat:@"%f", coord.latitude];
longitude.text = [NSString stringWithFormat:@"%f", coord.longitude];
altitude.text = [NSString stringWithFormat:@"%f", newLocation.altitude];
// 實際應用中可在此停止更新以省電:[locManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(@"定位失敗: %@", error.localizedDescription);
// 處理權限拒絕、網路不可用等錯誤
}
- (void)dealloc {
[locManager stopUpdatingLocation];
locManager.delegate = nil;
[super dealloc];
}
@end
MainView.xib 進入 Interface BuilderReferencing Outlets 分別連接至 File's Owner 的 latitude、longitude、altitudeupdate Action (可選,供手動重新定位)
| 主題 | 說明 |
|---|---|
| 權限聲明 | iOS 8+ 需在 Info.plist 加入 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysAndWhenInUseUsageDescription,否則定位失敗無提示 |
| 精度與耗電 | kCLLocationAccuracyBest 耗電最多;導航用 kCLLocationAccuracyBestForNavigation;一般 App 建議 kCLLocationAccuracyHundredMeters |
| 背景定位 | 需開啟 Background Modes → Location updates,並設定 allowsBackgroundLocationUpdates = YES |
| 模擬器測試 | Xcode Debug → Simulate Location 可模擬城市、騎行、駕駛、GPX 路徑 |
| iOS 14+ 隱私 | 用戶可選擇「精確位置」關閉,App 只能獲取模糊位置 (約 10km 範圍) |
startMonitoringForRegion: 進入/離開指定區域觸發通知visitMonitoring 記錄用戶停留地點CLGeocoder 經緯度 ↔ 地址字串互轉