play2win
play2win

Reputation: 331

Swift - Getting GPS coordinates from didUpdateLocations taking too long to return values

Problem: I need the location coordinates to be acquired before getReports() is executed in viewDidLoad(). As you can see, I'm calling startLocationUpdates first in viewDidLoad(). Unfortunately, there is a delay between calling startLocationUpdates() and didUpdateLocations getting called. This delay is causing the latitude and longitude coordinates to be zero every time prior to executing getReports().

How can I be sure that didUpdateLocations gets called BEFORE getReports() so that the latitude and longitude values are set properly?

override func viewDidLoad() {
    super.viewDidLoad()

    self.startLocationUpdates()

    // Do any additional setup after loading the view.
    self.mapView.delegate = self

    if mblnLocationAcquired {
        getReports()
    }

    }

}

func startLocationUpdates() {
    var currentLocation = CLLocation()

    mLocationManager.desiredAccuracy = kCLLocationAccuracyBest
    mLocationManager.delegate = self
    //mLocationManager.requestWhenInUseAuthorization()
    mLocationManager.requestWhenInUseAuthorization()
    mLocationManager.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    let location = locations.last as CLLocation
    self.mdblLat = location.coordinate.latitude
    self.mdblLong = location.coordinate.longitude

    println("didUpdateLocation  \(location.coordinate.latitude), \(location.coordinate.longitude)")
    mLocationManager.stopUpdatingLocation()
    mblnLocationAcquired = true
}

Upvotes: 0

Views: 1739

Answers (1)

matt
matt

Reputation: 534925

How can I be sure that didUpdateLocations gets called BEFORE getReports() so that the latitude and longitude values are set properly?

Simple. Don't call getReports() until after the latitude and longitude are set properly! You are making a huge mistake by turning off updates as soon as the first update arrives. Keep in mind that it takes significant time for the GPS to "warm up" after you start location updates. You will receive numerous initial updates in which the location is meaningless or miles off. You need to use the accuracy reading of the location in order to wait until you have a good value before you display anything.

Upvotes: 1

Related Questions