如何过滤无效的位置更新iOS

时间:2017-01-12 20:50:15

标签: ios swift cllocationmanager

我每隔1分钟使用CCLocationManager跟踪位置,这是我的didUpdateLocation委托方法:

func changeLocationAccuracy() {
    switch locationManager.desiredAccuracy {
    case kCLLocationAccuracyBest:
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.distanceFilter = 99999
    case kCLLocationAccuracyThreeKilometers:
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
    default: break
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let newLocation = locations.last else {
        return
    }

    let interval = newLocation.timestamp.timeIntervalSinceNow

    if abs(interval) > 5 || locationManager.desiredAccuracy != kCLLocationAccuracyBest {
        return
    }

    if newLocation.horizontalAccuracy < 0 {
        return
    }

    if currentLocation != nil && newLocation.timestamp.timeIntervalSince(currentLocation.timestamp) < 0 {
        return
    }

    currentLocation = newLocation

    print("interval: \(interval)")
    print("desiredAccuracy: \(locationManager.desiredAccuracy)")
    print("accuracy: \(newLocation.horizontalAccuracy)")

    timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(LocationService.changeLocationAccuracy), userInfo: nil, repeats: false)
    changeLocationAccuracy()
}

正如您在上面所看到的,我过滤掉了无效的位置,但问题是我的距离正在变化,而不会移动我的手机。这是我的日志数据:

interval: -0.0140599608421326
desiredAccuracy: -1.0
accuracy: 90.8123422472749
distance : 113.473282606026
-----------
interval: -0.0128610134124756
desiredAccuracy: -1.0
accuracy: 90.8123422472749
distance : 113.473282606026
-----------
interval: -0.00315600633621216
desiredAccuracy: -1.0
accuracy: 2000.0
distance : 180.768761850842
-----------
interval: -0.00381100177764893
desiredAccuracy: -1.0
accuracy: 2000.0
distance : 180.768761850842
-----------
interval: -0.0131250023841858
desiredAccuracy: -1.0
accuracy: 219.000225316427
distance : 0.763731059143118
-----------
interval: -0.0137189626693726
desiredAccuracy: -1.0
accuracy: 219.000225316427
distance : 0.763731059143118

任何解决方案? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可能只是希望获得的准确度高于可以提供的准确度。首先,手机最初使用的是其他车载传感器,而不是GPS。其次,GPS系统本身并不是特别准确。因此,即使你是静止不动的,你可能会觉得随着时间的推移,手机认为你会发生微小的变化,因为不同的传感器会变热,而且仅仅因为最准确的传感器GPS并不是那么准确。