接收JSON数据但未打印任何内容(快速)?

时间:2019-03-21 19:24:09

标签: ios json swift

因此,我正在尝试从this API中获取数据,目前有一个功能可以测试我是否接收到任何数据,并且什么也不打印。我没有收到任何错误消息,所以我必须正确获取一些数据吗?我正在使用相同的函数将另一个文件中的JSON解析为不同的API,并且该模板正在工作,所以不知道我在做什么错。

这是API的结构:

struct Currency: Codable {
    let name: String
    let rate: Double
    let symbol: String

}

这是从API解析JSON,将其存储在数组中并进行打印(以测试其是否有效)。

// Arrays to store our currency JSON data
    var currencies = [String]()

@objc func fetchJSON() {
        // API for Currency data
        let urlString = "https://api.coinstats.app/public/v1/fiats"

        if let url = URL(string: urlString) {           // If URL is valid
            if let data = try? Data(contentsOf: url) {  // Create a Data object and return the contents of the URL
                // We're OK to parse!
                parse(json: data)
                return
            }
        }
        // Show Error if failed
        performSelector(onMainThread: #selector(showError), with: nil, waitUntilDone: false)
    }

    func parse(json: Data) {
        // Creates an instance of JSONDecoder, which is dedicated to converting between JSON and Codable objects.
        let decoder = JSONDecoder()

        // Call the decode() method on that decoder, asking it to convert our json data into a Cryptocurrencies object.
        if let jsonFiat = try? decoder.decode(Currency.self, from: json) {
            currencies = [jsonFiat.name]
            test()
        } else {
            performSelector(onMainThread: #selector(showError), with: nil, waitUntilDone: false)
        }
    }

    func test(){
     print(currencies)
    }

1 个答案:

答案 0 :(得分:1)

您需要解码为数组,然后映射该数组

if let jsonFiat = try? decoder.decode([Currency].self, from: json) {
    currencies = jsonFiat.map { $0.name }
    test()
}

下面是我在操场上的测试代码

struct Currency: Codable {
    let name: String
    let rate: Double
    let symbol: String
}

var currencies = [String]()

func fetchJSON() {
    let urlString = "https://api.coinstats.app/public/v1/fiats"        
    if let url = URL(string: urlString), let data = try? Data(contentsOf: url) {  // Create a Data object and return the contents of the URL
        // We're OK to parse!
        parse(json: data)
        return        
    } else {
        print("Download failed")
    }
}

func parse(json: Data) {
    print(json)
    // Creates an instance of JSONDecoder, which is dedicated to converting between JSON and Codable objects.
    let decoder = JSONDecoder()

    // Call the decode() method on that decoder, asking it to convert our json data into a Cryptocurrencies object.
    if let jsonFiat = try? decoder.decode([Currency].self, from: json) {
         currencies = jsonFiat.map { $0.name }
        test()
    } else {
        print("decode failed")
    }
}

func test(){
    print(currencies)
}

fetchJSON()