Tommy K
Tommy K

Reputation: 1807

how to wait for requestLocation before proceeding?

I'm requesting user location when a button is pressed which then triggers an API call. However I don't want to make this API call before the latitude/longitude values are obtained from the requestLocation() call. I thought I could just poll with a while loop checking if my optional variables latitude == nil || longitude == nil, but then just sits in the while loop forever. I need to have some kind of waiting for those values because if I don't it just would send nils to the API call, since it takes a few seconds to get the location. What would I do to make sure the API request isn't called until the latitude/longitude values are set from the requestLocation() call?

Upvotes: 2

Views: 1967

Answers (2)

Chandan
Chandan

Reputation: 757

Call your api from this delegate method of CLLocationManagerDelegate

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    locationManager.stopUpdatingLocation()
     let location = locations.last! as CLLocation

    latittude = String(format: "%f", location.coordinate.latitude)
    longitude = String(format: "%f", location.coordinate.longitude)

// call your api from here

}

HOPE THIS WILL HELP YOU.

THANKS

Upvotes: 2

Mukul More
Mukul More

Reputation: 564

Make the api call in the delegate where the location is being updated. DidUpdateLocation. I don't remember the name exactly.

Didupdatelocations first location will be an older location so make sure the location you used to send the request is close to accurate.

Upvotes: 0

Related Questions