xcode 位置管理器给出空坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19603830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 04:11:35  来源:igfitidea点击:

location manager giving null coordinates

iosxcodecore-location

提问by user2402616

The following code results in null coordinates. The weird thing is the UIAlert prompting the app to use current location appears briefly before the user can select yes.

以下代码导致空坐标。奇怪的是,在用户选择是之前,提示应用程序使用当前位置的 UIAlert 会短暂出现。

My code which i have used :

我使用过的代码:

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);

The NSLog prints 0.0000000for both coordinates.

NSLog 打印0.0000000两个坐标。

Thanks!

谢谢!

回答by Khanh Nguyen

The reason you're getting 0 is because the location manager hasn't collected any data at that point (it has started thought)

你得到 0 的原因是因为位置管理器当时没有收集任何数据(它已经开始考虑)

You need to set your class as the delegate of the location manager (ie supplying a function that is called whenever a new location is retrieved), and also retain your location manager.

您需要将您的类设置为位置管理器的委托(即提供一个在检索新位置时调用的函数),并保留您的位置管理器。

// 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);
}