swift - 序列化 JSON 数据时的空对象

标签 swift codable

<分区>

我是 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!
}

enter image description here enter image description here

最佳答案

您的代码是异步的,因此当您强制解包它时位置变量为 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)
}

关于swift - 序列化 JSON 数据时的空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466040/

相关文章:

swift - 我怎样才能使我的 UIView 在没有自动布局的情况下始终与屏幕右侧齐平?

ios - 想要在 Alamofire reponseJSON block 中使用 UIAlertController

swift - 如何在 firebase 观察者路径中使用通配符?

ios - 如何在 Codable 类型中使用 Any

ios - 如果不在 Swift 的内部范围内使用,是否不保留闭包变量?

ios - 手动解码 Codable 类的非 Codable 属性

swift - 在 Swift 中同时实现 Codable 和 NSManagedObject

ios - 核心数据保存关闭

json - 如何使用 swift 4.1 codable(json 解码)过滤无效数据

ios - 在 Swift 中将按日期分隔的部分添加到 UITableView