相同的代码,我假设设备实际上出于某种原因更新了两次位置,即使我只调用了一次 startUpdatingLocation() 并且我在 didUpdateLocations 中运行了一些 stopUpdatingLocations()
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
let loc: CLLocation = locations[locations.count - 1]
let id = 0
let type = 0
let number = 0
createNewDataPoint(id, loc: loc, type: type, number: number)
}
在这种情况下,createNewDataPoint 被调用两次,创建了 2 个新数据点。它只在模拟器中发生一次,所以我假设它与实际设备和 GPS 有关,因为模拟器伪造了它的位置。
startUpdatingLocation() 仅在我的代码中出现一次,在一个按钮上。基本上,您单击按钮,进入 manager.startUpdatingLocations(),didUpdateLocations 在模拟器上点击一次,在设备上点击两次(相同的坐标)并创建 2 个新数据点。
唯一提到任何相关内容的其他代码是设置准确性、过滤器、授权请求和前面提到的 startUpdatingLocation()。我可以做些什么来确保我不会创建两倍于所需的数据点?
最佳答案
位置管理器委托(delegate)方法可以非常频繁地随时调用。
但是,您可以应用以下算法来保护自己:
- 创建一个全局
bool
saydidFindLocation
。 - 在调用
startUpdatingLocation
时将didFindLocation
设置为false
。 - 内部委托(delegate)回调
didUpdateLocations:
,如果didFindLocation
为false
,则将didFindLocation
设置为true
然后调用stopUpdatingLocation
。
希望这对您有所帮助。
关于ios - locationManager didUpdateLocations 在设备上触发两次,在模拟器上只触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492023/