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

sdo*_*ble 12 cllocationmanager ios swift

相同的代码,我假设设备实际上是因某种原因更新了位置两次,即使我只调用一次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)
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,createNewDataPoint被调用两次,创建2个新数据点.它只在模拟器中发生一次,所以我假设它与实际设备和GPS有关,因为模拟器伪造了它的位置.

startUpdatingLocation()只在我的代码中一次,在一个按钮上.基本上,你单击按钮,去go manager.startUpdatingLocations(),didUpdateLocations在模拟器上点击一次,在设备上点击两次(相同的坐标),它创建2个新的数据点.

提及任何相关内容的唯一其他代码是设置准确性,过滤器,授权请求以及前面提到的startUpdatingLocation().有什么我可以做的,以确保我没有创建两倍于必要的数据点?

Abh*_*nav 17

可以在任何时候非常频繁地调用位置管理器委托方法.

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

  1. 创造全球化的bool说法didFindLocation.
  2. 设置didFindLocationfalse您打电话时startUpdatingLocation.
  3. 在委托内部回调didUpdateLocations:,如果didFindLocationfalse,则设置didFindLocationtrue然后调用stopUpdatingLocation.

希望这可以帮助.


And*_* M. 12

最好的方法是做如下:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    manager.delegate = nil
}
Run Code Online (Sandbox Code Playgroud)


Zum*_*med 6

iOS 10.0+的最佳解决方案

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [locationManager stopUpdatingLocation]; // stop location manager
    locationManager.delegate = nil;
    //Your logics... 
    //This will be called only one time now.
}
Run Code Online (Sandbox Code Playgroud)

但是别忘了再次设置委托.