【发布时间】:2013-02-07 19:40:55
【问题描述】:
当locationManager:didUpdateLocations:(或其已弃用的等效locationManager:didUpdateToLocation:fromLocation:)消息发送到CLLocationManagerDelegate 时,CLLocationManagerDelegate Protocol Reference 声明:
当此消息传递给您的代表时,新的 位置数据也可以直接从 CLLocationManager 获得 目的。 newLocation 参数可能包含缓存的数据 来自先前使用定位服务。您可以使用 位置对象的时间戳属性来确定最近的位置 位置数据是。
但是,实际上,CLLocationManager 的 location 属性不会更新。为什么不呢?
我创建了一个示例项目来演示这一点: https://github.com/sibljon/CoreLocationDidUpdateToLocationBug
相关代码在JSViewController,sn-p如下:
- (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];
}
【问题讨论】:
-
什么意思,没更新?你得到的第一个值可能是一个缓存值,然后你应该得到一个真实的值,假设你正在获取数据。你是在设备上测试这个吗?
-
您注意到您总是打印新位置而不是旧位置,对吗?这实际上并没有做任何事情,只会阻止您查看 newLocation 和 oldLocation 是否不同。我建议:也许 didUpdateToLocation 正在被调用,但您没有新的位置,只是获取前一个位置。这可能会发生,文档对此进行了讨论。
-
@CarlVeazey 感谢您的更正。
-
@all:我每次都能重现这个错误。以下是重现的步骤: 1. 在github.com/sibljon/CoreLocationDidUpdateToLocationBug 下载我的示例项目 2. 在模拟器中运行 3. 将您的位置设置为 Apple (Debug->Location->Apple) 并观察控制台 4. 将您的位置设置为德国 (Debug ->Location->Custom) -- 纬度 51,经度 9 -- 并观察控制台 5。注意将位置更改为德国时的方式:newLocation == - [CLLocationManager location] ==
-
将位置从“Apple”切换到“Germany”时观察控制台输出。 newLocation 正确且 [CLLocationManager 位置] 错误:cl.ly/image/2c3z1s3c3r0n
标签: ios core-location cllocationmanager