当locationManager:didUpdateLocations:
(或其已弃用的等效项locationManager:didUpdateToLocation:fromLocation:
)消息发送到 时CLLocationManagerDelegate
,CLLocationManagerDelegate 协议参考声明:
当这条消息被传递给您的委托时,新的位置数据也可以直接从 CLLocationManager 对象中获得。newLocation 参数可能包含从先前使用位置服务缓存的数据。您可以使用位置对象的时间戳属性来确定位置数据的新近程度。
但是,在实践中,CLLocationManager
的location
属性不会更新。为什么不?
我创建了一个示例项目来演示这一点: 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];
}