The purpose of this code is that when you double tap on a MapKit view it will drop a pin on the map and get the latitude and longitude coordinates. When it drops the pin I want it to call an API and have that API return the city name. I want to display this city name by having a label over the map view that will update whenever you place a new pin.
When a pin is dropped this function is called:
func previewDataOnButton(){
print("PreviewDataOnButton Called")
theWeatherDataModel.callAPI(latitude: latitude!, longitude: longitude!)
cityStateLabel.text = theWeatherDataModel.cityName
print("PreviewDataOnButton Finished")
}
This function is in the view controller, and it calls a function in a separate model. The function it's calling looks like this:
func callAPI(latitude: String, longitude: String){
let baseURL = "https://api.weatherbit.io/v2.0/current?&lat=\(latitude)&lon=\(longitude)&key=\(apiKey)"
let urlComponents = URLComponents(string: baseURL)
let theURL = urlComponents?.url
let session = URLSession(configuration: .ephemeral)
let theTask = session.dataTask(with: theURL!) {
(data, response, error) in
if let actualError = error{
print("We got an error")
} else if let actualData = data, let actualResponse = response{
print("We got stuff back")
let parsedData = try? JSON(data: actualData)
//print("Data: \n\(String(describing: parsedData))")
if let theWeatherArray = parsedData?["data"]{
for(_, singleWeatherDictionary) in theWeatherArray{
self.cityName = singleWeatherDictionary["city_name"].string
}
}
} else {
print("How did I get here?")
}
print("Im done with the closure")
}
print("About to start the data task")
theTask.resume()
print("Started data task")
}
I placed print statements throughout the code to debug and it printed this:
PreviewDataOnButton Called
About to start the data task
Started data task
PreviewDataOnButton Finished
We got stuff back
Im done with the closure
From the output, it seems that the function in the view controller is finishing before the function in the model can finish its task and call the model. This is causing the label on the view to not update properly with the right city name because the function finishes before the API actually gets the city name. This is where I'm stuck, any help would be appreciated.