ios - 位置管理器给出空坐标

标签 ios xcode core-location

以下代码生成空坐标。奇怪的是提示应用程序使用当前位置的 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 的原因是因为位置管理器当时没有收集任何数据(它已经开始思考)

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

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

关于ios - 位置管理器给出空坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19603830/

相关文章:

swift - geocodeAddressString 不适用于 swift

ios - 如何获取通过 iphone 中的照片库选择的图像的名称?

ios - 多个 XIB 错误 : Could not load NIB in bundle

ios - 在重复的项目上使用源代码

objective-c - Unicode 格式化编译器警告 : Format specifies type 'unsigned short' but the argument has type 'int'

core-location - iBeacon 和 XCode - 使用 CoreLocation 进行发现并与 CoreBluetooth 连接

ios - GCKDeviceManager 协议(protocol) - didDisconnectWithError : and didDisconnectFromApplicationWithError:? 之间有什么区别

ios - 在 UI 测试中获取文本字符串的颜色

ios - 界面生成器中的组合框对象在哪里?

ios - 检测位置的微小变化