在 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)
}
}
我得到的错误是:Fetch Failed: Unknown Error,提示应用程序无法读取在线数据.这是什么原因造成的?
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屋!
查看全文