Reputation: 263
I am simply trying to get latitude and longitude of a city. But before alamofire can complete the request I receive the defined value of 0.0 which is not what I want. I do get the values of latitude and longitude but 0.0 has already been passed so the app takes that only.
I have tried completion block but it didn't work. I tried little tricks here and there but nothing worked. How should I improve this?
func getAddress(address:String){
let key : String = "<API_KEY>"
let postParameters:[String: Any] = [ "address": address,"key":key]
let url : String = "https://maps.googleapis.com/maps/api/geocode/json"
var lat = 0.0
var long = 0.0
Alamofire.request(url, method: .get, parameters: postParameters, encoding: URLEncoding.default, headers: nil).responseJSON {
response in if let receivedResults = response.result.value
{
let resultParams = JSON(receivedResults)
print(resultParams["status"]) // OK, ERROR
lat = resultParams["results"][0]["geometry"]["location"]["lat"].doubleValue// approximately latitude
long = resultParams["results"][0]["geometry"]["location"]["lng"].doubleValue // approximately longitude
print("Here i am \(self.destLatitude)")
}
self.destLatitude = lat
self.destLongitude = long
print("Here i am also \(self.destLatitude)")
}
}
Expected output is latitude and longitude of a place.
Upvotes: 0
Views: 149
Reputation: 285064
The network request works asynchronously, assign the values to the properties inside the completion handler
Alamofire.request(url, method: .get, parameters: postParameters, encoding: URLEncoding.default, headers: nil).responseJSON {
response in if let receivedResults = response.result.value
{
let resultParams = JSON(receivedResults)
print(resultParams["status"]) // OK, ERROR
lat = resultParams["results"][0]["geometry"]["location"]["lat"].doubleValue// approximately latitude
long = resultParams["results"][0]["geometry"]["location"]["lng"].doubleValue // approximately longitude
self.destLatitude = lat
self.destLongitude = long
print("Here i am \(self.destLatitude)")
}
}
Upvotes: 2