5

locationManager:didUpdateLocations:(或其已弃用的等效项locationManager:didUpdateToLocation:fromLocation:)消息发送到 时CLLocationManagerDelegateCLLocationManagerDelegate 协议参考声明:

当这条消息被传递给您的委托时,新的位置数据也可以直接从 CLLocationManager 对象中获得。newLocation 参数可能包含从先前使用位置服务缓存的数据。您可以使用位置对象的时间戳属性来确定位置数据的新近程度。

但是,在实践中,CLLocationManagerlocation属性不会更新。为什么不?

我创建了一个示例项目来演示这一点: https ://github.com/sibljon/CoreLocationDidUpdateToLocationBug

相关代码在 中JSViewController,其中的一个片段如下:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    self.locationManager.distanceFilter = 10000.0; // 10 km
    self.locationManager.delegate = self;
    self.locationManager.purpose = @"To show you nearby hotels.";
    [self.locationManager startUpdatingLocation];

    [self.locationManager startUpdatingLocation];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"New location: %@", newLocation);
    NSLog(@"Old location: %@", oldLocation);
    NSLog(@"- [CLLocationManager location]: %@", manager.location);
}

//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
//{
//    for (CLLocation *location in locations)
//    {
//        NSLog(@"Current location: %@", locations);
//    }
//    NSLog(@"- [CLLocationManager location]: %@", manager.location);
//}

#pragma mark - Notifications

- (void)appWillEnterForeground:(NSNotification *)notification
{
    [self.locationManager startUpdatingLocation];
}

- (void)appDidEnterBackground:(NSNotification *)notification
{
    [self.locationManager stopUpdatingLocation];
}
4

2 回答 2

1

我认为这是一个错误,我已经向 Apple 提交了错误报告。可以在 Open Radar 上找到错误报告的镜像:

http://openradar.appspot.com/radar?id=2682402

于 2013-02-07T19:40:55.043 回答
0

正如您在文档中所读到的,locationManagerDelegate 可能会将缓存的数据传递给回调方法。

这实际上经常发生,因此您需要做的是检查相对时间或当前时间的时间戳,newLocationoldLocation查看它们是否足够不同(差异有多大取决于您根据应用程序的需求来决定)。

以下是如何针对当前时间进行检查的片段:

    if ([newLocation.timestamp timeIntervalSinceNow] < 600) // 10 minutes
于 2013-02-07T22:53:18.250 回答