LocationManager didUpdateLocations在设备上触发两次,在模拟器上仅触发一次 [英] locationManager didUpdateLocations fires twice on device, only once on simulator

查看:67
本文介绍了LocationManager didUpdateLocations在设备上触发两次,在模拟器上仅触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相同的代码,我假设设备实际上出于某种原因更新了两次位置,尽管我只调用了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被调用两次,创建两个新的数据点。它只在模拟器中发生一次,所以我认为它与实际设备和GPS有关,因为模拟器伪造了它的位置。

startUpdatingLocation()在我的代码中只出现过一次,在按钮上。基本上,你只需点击按钮,进入管理器。startUpdatingLocations(),didUpdatingLocations在模拟器上点击一次,在设备上点击两次(相同的坐标),它就会创建两个新的数据点。

提到任何相关内容的唯一其他代码是设置准确性、过滤器、授权请求和前面提到的startUpdatingLocation()。我可以做些什么来确保我创建的数据点不会是所需的两倍?

推荐答案

可以非常频繁地随时调用位置管理器委托方法。

不过,您可以应用以下算法来保护自己:

  1. 创建全局booldidFindLocation
  2. 调用startUpdatingLocation时将didFindLocation设置为false
  3. 内部委托回调didUpdateLocations:,如果didFindLocationfalse,则将didFindLocation设置为true,然后调用stopUpdatingLocation

希望这能有所帮助。

这篇关于LocationManager didUpdateLocations在设备上触发两次,在模拟器上仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆