如何在 iOS 中从用户那里获取当前位置?
RedBlueThing 的答案对我来说效果很好。这是我如何做到的一些示例代码。
#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface yourController : UIViewController <CLLocationManagerDelegate> { CLLocationManager *locationManager; } @end
在初始化方法中
locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation];
回调函数
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude); NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude); }
在 iOS 6 中,委托功能已被弃用。新代表是
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
因此要获得新的职位使用
[locations lastObject]
在 iOS 8 中,应在开始更新位置之前明确询问权限
locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) [self.locationManager requestWhenInUseAuthorization]; [locationManager startUpdatingLocation];
您还必须为应用程序的 Info.plist 中的NSLocationAlwaysUsageDescriptionorNSLocationWhenInUseUsageDescription键添加一个字符串。否则调用startUpdatingLocation将被忽略,您的委托将不会收到任何回调。
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
startUpdatingLocation
最后,当您完成阅读位置时,请在合适的位置调用 stopUpdating 位置。
[locationManager stopUpdatingLocation];