sdouble sdouble -5 years ago 395
iOS Question

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]) {
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download