如何在 iOS 中从用户那里获取当前位置?
最佳答案
RedBlueThing 的答案对我来说效果很好。这是我如何做到的一些示例代码。
标题
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
主文件
在init方法中
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
在 iOS 6 中,委托(delegate)函数已被弃用。新代表是
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
因此获得新的位置使用
[locations lastObject]
iOS 8
在 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];
您还必须为 NSLocationAlwaysUsageDescription
添加一个字符串或 NSLocationWhenInUseUsageDescription
应用程序 Info.plist 的键。否则对 startUpdatingLocation
的调用将被忽略,您的委托(delegate)将不会收到任何回调。
最后,当你读完位置后,在合适的地方调用 stopUpdating location。
[locationManager stopUpdatingLocation];
关于ios - 如何在 iOS 中从用户那里获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4152003/