I am relatively new to Swift so please excuse any rookie errors. I am retrieving some data from a web service and serialising the data into an object. However, when I return this object from the enclosing function, it is always null. If I run this code all in the ViewController however, it works fine. It only seems to fail when I split my code out into separate classes/methods (I am trying to implement better practises). I should also add that no error is printed from the print(error) statement.
Thanks in advance for any help!
func getLocationData(lat: String, long: String) -> Location {
locationUrl += lat + "&lon=" + long
print("Location query: " + locationUrl)
let request = NSMutableURLRequest(url: NSURL(string: locationUrl)! as URL)
request.httpMethod = "GET"
var location: Location?
_ = URLSession.shared.dataTask(with: request as URLRequest, completionHandler:
{(data, response, error) -> Void in
if (error != nil) {
print("Error making requets to web service")
} else {
do {
location = try JSONDecoder().decode(Location.self, from: data!)
} catch let error as NSError {
print(error)
}
}
}).resume()
return location!
}