didUpdateToLocation
回调可能由于许多原因而更新,处理这个问题的好策略是逐步过滤基于时间戳的结果,然后要求准确性。
苹果提供的LocateMe sample app一个很好的例子:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
// test the measurement to see if it is more accurate than the previous measurement
if (self.bestEffortAtLocation == nil || self.bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy)
{
// store the location as the "best effort"
self.bestEffortAtLocation = newLocation;
// test the measurement to see if it meets the desired accuracy
//
// IMPORTANT!!! kCLLocationAccuracyBest should not be used for comparison with location coordinate or altitidue
// accuracy because it is a negative value. Instead, compare against some predetermined "real" measure of
// acceptable accuracy, or depend on the timeout to stop updating. This sample depends on the timeout.
//
if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
// we have a measurement that meets our requirements, so we can stop updating the location
//
// IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
//
[self stopUpdatingLocation:NSLocalizedString(@"Acquired Location", @"Acquired Location")];
}
}
}
太好了,谢谢! – user1553961
谢谢,但如果我想让位置服务保持打开状态呢? stopUpdating可能会阻止位置管理器不行? – Dejell
此代码允许位置管理器根据需要进行更新以确定用户所需的准确度。在哪一点上,电源管理停止更新是合乎情理的。如果您的应用程序需要在用户更改位置时监视用户,那么您可以注册重要更改:'[locationManager startMonitoringSignificantLocationChanges];'请参阅[docs](https://developer.apple.com/library/ios/documentation/ userexperience /概念性/ LocationAwarenessPG/CoreLocation/CoreLocation.html) – cleverbit