提取JSON,将其解析为数组,然后在Swift中打印

时间:2018-09-04 16:48:57

标签: swift swift-playground

我正在尝试从API提取json数据,将其解析为struct数组,然后打印该数组。但是,当我尝试将其打印出来时,仅返回一个空白数组。我试图了解如何为异步操作编写代码,并且不确定从何处去。有人能指出我正确的方向吗? 我正在使用Xcode 9,Swift 4在Playgrounds上进行尝试。

import Foundation

struct Item: Decodable {
    var userId: Int?
    var id: Int?
    var title: String?
    var body: String?
}

var items = [Item?]()

let completionHandler = { (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            print("Error occured: \(error.debugDescription)")
        }
        
        let decoder = JSONDecoder()
        do {
            items = try decoder.decode([Item].self, from: data!)
            print(items)
        } catch {
            print("Error: Unable to fetch data")
        }
    }

func getJson() {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: completionHandler)
    task.resume()
    print(items)
}

getJson()

1 个答案:

答案 0 :(得分:0)

要能够在Playground中运行异步内容,您必须添加

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

三个注意事项:

  1. print之后的resume行毫无意义。它将始终打印一个空数组。完成处理程序中的print行显示了实际结果
  2. items声明为

    var items = [Item]()
    

    JSONDecoder()返回非可选内容或引发错误

  3. 此特定的API始终发送所有字段,因此您甚至可以将所有struct成员声明为非可选

    struct Item: Decodable {
        var userId: Int
        var id: Int
        var title: String
        var body: String
    }
    
相关问题