在 iOS 中取得裝置位置,最常見的方式是使用 CoreLocation Framework。透過 CLLocationManager,可以取得經緯度、精度、高度等資訊,也能計算兩個座標之間的距離。
首先要把 CoreLocation.framework 加入專案,並在程式碼中引入:
#import <CoreLocation/CoreLocation.h>
若要接收定位更新,ViewController 需要遵循 CLLocationManagerDelegate。
@interface GPSViewController : UIViewController <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
locationManager 建議保存為類別屬性,不要只用區域變數,否則可能因物件被釋放而無法收到後續回呼。
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D coordinate = newLocation.coordinate;
NSLog(@"緯度: %f, 經度: %f", coordinate.latitude, coordinate.longitude);
[self.locationManager stopUpdatingLocation];
CLLocationDistance distance = [newLocation distanceFromLocation:oldLocation];
NSLog(@"距離: %f", distance);
}
若只需要取得一次位置,可以在收到座標後呼叫 stopUpdatingLocation。若需要持續追蹤,則可保留更新狀態,並依需求調整 desiredAccuracy 以平衡精度與耗電。