Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locationManager didUpdateLocations fires twice on device, only once on simulator

Same code, I'm assuming that the device is actually updating the location twice for some reason, even though I only call startUpdatingLocation() once and I run some stopUpdatingLocations() inside of didUpdateLocations

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)
}

In this case, createNewDataPoint gets called twice, creating 2 new datapoints. It only happens once in the simulator, so I'm assuming it has something to do with the actual device and the GPS since the simulator fakes its location.

startUpdatingLocation() is only in my code one time, on a button. Basically, you click the button, go go manager.startUpdatingLocations(), didUpdateLocations hits once on simulator, twice on device (identical coordinates) and it creates 2 new data points.

The only other code that mentions anything related is setting the accuracy, filter, authorization requests, and the previously mentioned startUpdatingLocation(). Is there something I can do to make sure I'm not creating twice as many data points as necessary?

like image 936
sdouble Avatar asked Nov 03 '15 05:11

sdouble


2 Answers

The best way is do as following:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    manager.delegate = nil
}
like image 163
Andrey M. Avatar answered Oct 22 '22 10:10

Andrey M.


Location Manager delegate methods can be called very frequently and at any time.

You may however, apply following algorithm to safeguard yourself:

  1. Create a global bool say didFindLocation.
  2. Set didFindLocation to false when you call startUpdatingLocation.
  3. Inside delegate call back didUpdateLocations:, if didFindLocation was false, set didFindLocation to true and then call stopUpdatingLocation.

Hope this helps.

like image 18
Abhinav Avatar answered Oct 22 '22 11:10

Abhinav