有时候iOS会从缓存中获取位置信息,导致精度不够准确,因此需要避免这种情况。以下是获取准确位置的代码:
更新: “由于返回初始位置可能需要几秒钟时间,定位管理器通常会立即提供先前缓存的位置数据,然后在可用时提供更实时的位置数据。因此,在执行任何操作之前,检查任何位置对象的时间戳始终是一个好主意。”
参考资料:
https://developer.apple.com/reference/corelocation/cllocationmanager
注意:您可以根据设备(如iPod和iPad)的需要调整精度。
//MARK: Location delgates
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if locations.count > 0
{
let location = locations[locations.count-1]
let maxAge:TimeInterval = 60;
let requiredAccuracy:CLLocationAccuracy = 100;
let locationIsValid:Bool = Date().timeIntervalSince(location.timestamp) < maxAge && location.horizontalAccuracy <= requiredAccuracy;
if locationIsValid
{
NSLog(",,, location : %@",location);
NSLog("valid locations.....");
}
}
}
我会对位置进行排序,并仅在最后一个位置不太旧时才采用它:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let sortedLocations = locations.sorted { (l1, l2) -> Bool in
return l1.timestamp.compare(l2.timestamp) != .orderedDescending
}
if let newestLocation = sortedLocations.last{
if Date().timeIntervalSince(newestLocation.timestamp) < 60{
//TODO: Use the location
}
}
}
是的,就像@chirag shah评论的那样,我们绝对需要进行检查。我的建议是我们应该知道缓存技术已经被修改了。而且仅仅检查时间戳是不够的,我们还必须关注失败的情况。这里是Objective C代码
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation* location = [locations lastObject];
NSDate* locationTimestamp = location.timestamp;
NSTimeInterval cachedBefore = [locationTimestamp timeIntervalSinceNow];
if (fabs(cachedBefore) < 60.0) {
// Implement your code here
}else{
// Try again or wait for fetching location
}
}