在SwiftUI中解码汇率JSON [英] Decoding Exchange Rate JSON in SwiftUI
本文介绍了在SwiftUI中解码汇率JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解码由提供的 https://api.exchangeratesapi.io/latest 汇率API.我正在应用几本在线上找到的教程,但是当我应用自己的详细信息时,会出现错误.我的代码如下:
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]
}
检索数据的功能:
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()
}
我的观点:
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?
与我的网络连接无关;如果我应用其他JSON,则此方法效果很好.
It has nothing to do with my network connection; if I apply another JSON this approach works fine.
任何帮助将不胜感激.
推荐答案
您可以这样阅读:
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()
}
这篇关于在SwiftUI中解码汇率JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文