<分区>
我是 Swift 的新手,所以请原谅任何菜鸟错误。我正在从 Web 服务中检索一些数据并将数据序列化为一个对象。但是,当我从封闭函数返回此对象时,它始终为空。但是,如果我在 ViewController 中运行这段代码,它就可以正常工作。当我将代码拆分为单独的类/方法时,它似乎只会失败(我正在尝试实现更好的实践)。我还应该补充一点,print(error) 语句没有打印错误。
在此先感谢您的帮助!
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!
}