以下代码导致空坐标。奇怪的是,在用户选择是之前,UIAlert会提示应用程序使用当前位置。
我用过的代码:
CLLocationManager *locationManager;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
float latitude = locationManager.location.coordinate.latitude;
float longitude = locationManager.location.coordinate.longitude;
NSLog(@"%.8f",latitude);
NSLog(@"%.8f",longitude);
NSLog为两个坐标打印0.0000000
。
谢谢!
答案 0 :(得分:7)
您获得0的原因是因为位置管理员此时没有收集任何数据(已经开始考虑)
您需要将您的类设置为位置管理器的委托(即提供在检索新位置时调用的函数),并保留您的位置管理器。
// Inside .m file
@interface MyClass () <CLLocationManagerDelegate> // Declare this class to implement protocol CLLocationManagerDelegate
@property (strong, nonatomic) CLLocationManager* locationManager; // Retains it with strong keyword
@end
@implementation MyClass
// Inside some method
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
// Delegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation* loc = [locations lastObject]; // locations is guaranteed to have at least one object
float latitude = loc.coordinate.latitude;
float longitude = loc.coordinate.longitude;
NSLog(@"%.8f",latitude);
NSLog(@"%.8f",longitude);
}