Decoding Exchange Rate JSON in SwiftUI

笑着哭i 提交于 2021-01-29 20:10:44

问题


I am trying to decode https://api.exchangeratesapi.io/latest, provided by Exchange Rates API. I'm applying several tutorials I found online, but when I apply my own details, I get an error. My code looks as following:

struct Response: Codable {
    var results: [Result]
}

struct Result: Codable {
    let base: String
    let date: String
    let rates: [String:Double]
}

The function to retrieve the data:

func loadData() {
    guard let url = URL(string: "https://api.exchangeratesapi.io/latest") else {
        print("Invalid URL")
        return
    }
    let request = URLRequest(url: url)
    URLSession.shared.dataTask(with: request) { data, response, error in
        if let data = data {
            if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                // we have good data – go back to the main thread
                DispatchQueue.main.async {
                    // update our UI
                    self.results = decodedResponse.results
                }
                // everything is good, so we can exit
                return
            }
        }
        // if we're still here it means there was a problem
        print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
    }.resume()
}

And my view:

import SwiftUI

struct ExchangeRateTest: View {
    @State private var results = [Result]()

    var body: some View {
                List(results, id: \.base) { item in
            VStack(alignment: .leading) {
                Text(item.base)
            }
        }.onAppear(perform: loadData)
    }
}

The error I get is: Fetch Failed: Unknown Error, suggesting that the app is not able to read the online data. What can cause this?

It has nothing to do with my network connection; if I apply another JSON this approach works fine.

Any help would greatly be appreciated.


回答1:


you can read like this:

struct RateResult: Codable {
    let rates: [String: Double]
    let base, date: String
}

struct ContentView: View {
    @State private var results = RateResult(rates: [:], base: "", date: "")

    func loadData() {
        guard let url = URL(string: "https://api.exchangeratesapi.io/latest") else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(RateResult.self, from: data) {
                    // we have good data – go back to the main thread
                    DispatchQueue.main.async {
                        // update our UI
                        self.results = decodedResponse
                    }
                    // everything is good, so we can exit
                    return
                }
            }
            // if we're still here it means there was a problem
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }


来源:https://stackoverflow.com/questions/61443473/decoding-exchange-rate-json-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!