I just started coding in Swift and I have the following code which parses JSON
func parse (latitude: Double, longtitude: Double){
let jsonUrlString = "https://api.darksky.net/forecast/apiKey/\(latitude),\(longtitude)"
guard let url = URL(string: jsonUrlString) else{
return
}
var information: forecast?
URLSession.shared.dataTask(with: url) { (data, res, err) in
guard let data = data else {
return
}
do {
let json = try JSONDecoder().decode(forecast.self, from: data)
self.info = json
} catch {
print("didnt work")
}
}.resume()
processJson(info)
}
My problem is that I want to pass data that is stored in JSON to a variable in the class to be processed using processJson function but since the dataTask function does not return any values, and JSON variable is locally stored I cannot process info variable outside the class (it always returns nil). I was wondering what is the solution to this problem? I'm facing the same problem with weather.getCoordinate().
URLSessionto make your request to the API, butURLSessionmake the call to the API asynchronously so the response of the request is handled using closures, this means that the line after theresumeyou're setting doesn't work at all because it will be called before the request finish and you variable is set. You should move it after set the variable in the closure