2

以下代码导致空坐标。奇怪的是,提示应用程序使用当前位置的 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两个坐标。

谢谢!

4

1 回答 1

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);
}
于 2013-10-26T07:01:40.037 回答