ios - locationManager didUpdateLocations 在设备上触发两次,在模拟器上只触发一次

标签 ios swift cllocationmanager

相同的代码,我假设设备实际上出于某种原因更新了两次位置,即使我只调用了一次 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)方法可以非常频繁地随时调用。

但是,您可以应用以下算法来保护自己:

  1. 创建一个全局 bool say didFindLocation
  2. 在调用 startUpdatingLocation 时将 didFindLocation 设置为 false
  3. 内部委托(delegate)回调 didUpdateLocations:,如果 didFindLocationfalse,则将 didFindLocation 设置为 true 然后调用 stopUpdatingLocation

希望这对您有所帮助。

关于ios - locationManager didUpdateLocations 在设备上触发两次,在模拟器上只触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492023/

相关文章:

iphone - CLLocationManager 误差范围

ios - 无法将类型 '[String]' 的值分配给类型“String”? swift 2

ios - CC UITouches 忽略第二次触摸

ios - Xcode 中带有两个 slider 旋钮的 slider

swift - 从 AppDelegate 访问 UINavigationController

ios - CLLocationManager 默认坐标值

ios - 尽管用户已终止应用程序并检查 iOS 中的设备位置,如何保持 iOS 应用程序进程始终运行?

ios - 异步 HTTP 响应在完成请求后保持几秒钟

ios - 改变方向时 UIScrollView 的大小

html - Swift 从 Webview 中获取 HTML 数据