序列化JSON数据时为Null对象

时间:2019-06-05 18:22:54

标签: swift codable

我对Swift还是比较陌生,所以请原谅任何新秀错误。我正在从Web服务中检索一些数据,并将数据序列化为一个对象。但是,当我从封闭函数返回此对象时,它始终为null。如果我在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!
}

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码是异步的,因此当您由于未返回响应而强行打开它时,位置var为nil,您需要完成

func getLocationData(lat: String, long: String,completion:@escaping (Location?) -> ()) {
    locationUrl += lat + "&lon=" + long
    print("Location query: " + locationUrl)

    var request = URLRequest(url: URL(string: locationUrl)!)
    request.httpMethod = "GET" 
    _ = 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 {
                    let location = try JSONDecoder().decode(Location.self, from: data!)
                    completion(location)
                } catch {
                    print(error)
                    completion(nil)
                }
            }
    }).resume()

}

致电

getLocationData(lat:////,long:////) { loc in 
  print(loc)
}