我的目标是知道用户何时旅行,即使该应用被杀或在后台。所以我实现了这个:
let locationManager = CLLocationManager()
private func setupLocationManager(){
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
locationManager.allowsBackgroundLocationUpdates = true
locationManager.activityType = .otherNavigation
}
func startSignificantChangeLocationUpdates() {
guard CLLocationManager.significantLocationChangeMonitoringAvailable() else {
logger.error("significantLocationChangeMonitoringAvailable returned false")
return
}
setupLocationManager()
locationManager.startMonitoringSignificantLocationChanges()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// only save data above magical 5m/s => 18km/h
var filteredLocations = locations.filter{$0.speed > 5}
//only save the fastest item if multiple data is delived
filteredLocations = filteredLocations.sorted { (l1, l2) -> Bool in
l1.speed > l2.speed
}
if let fastestLocation = filteredLocations.first{
if (filteredLocations.count > 0){
//save to DB
locationModel.addLocations(clLocations: [fastestLocation])
}
}
}
我的问题是这不是很准确。即使我乘坐火车10分钟内行驶超过10公里,我也只得到2或3个数据点,说我只走了2分钟。
我该如何改进? kCLLocationAccuracyNearestTenMeters
正在消耗大量精力。如果我与Moves比较,那么数据非常准确。但是,当我尝试保护用户隐私时,我不想整合他们的SDK。