【发布时间】:2021-04-23 22:54:05
【问题描述】:
我有一个货币 API,它返回一个包含奇怪排列的 JSON 对象:基础货币用作标签。典型的货币 API 具有“base”、“date”、“success”和“rates”等标签,但此 API 没有这些标签。
{
"usd": {
"aed": 4.420217,
"afn": 93.3213,
"all": 123.104693,
"amd": 628.026474,
"ang": 2.159569,
"aoa": 791.552347,
"ars": 111.887966,
"aud": 1.558363,
"awg": 2.164862,
"azn": 2.045728,
"bam": 1.9541,
"bbd": 2.429065,
"bch": 0.001278
}
}
顶部的“usd”(美元)称为基础货币或本国货币。目前,存储结构和状态参数被硬编码为“usd”,这防止使用与其他基础货币的汇率。汇率 API 适用于美元基础货币。
我需要帮助进行修改,以便下载不同基础货币的汇率。例如,我可以在存储模型和状态参数中使用字符串变量吗?任何启发将不胜感激。
struct RateResult: Codable {
let usd: [String: Double]
}
@State private var results = RateResult(usd: [:])
struct ContentView: View {
var body: some View {
}
func UpdateRates() {
let baseUrl = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"
let baseCur = baseCurrency.baseCur.baseS // usd
let requestType = ".json"
guard let url = URL(string: baseUrl + baseCur + requestType) 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
// save off currency exchange rates
}
// everything is good, so we can exit
return
}
}
// if we're still here it means there was a problem
print("Currency Fetch Failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
【问题讨论】:
-
很难理解这个问题是关于什么的,它真的是一个 SwiftUI 问题还是关于如何处理你的数据结构甚至如何下载?