我是学习Swift和SwiftUI的初学者。我想学习如何使用API和解码JSON。我在YouTube上找到了tutorial。它与视频中显示的iTunes API一起使用。然后,我将其替换为API about the Coronavirus。不幸的是,此后它始终在控制台中显示“获取失败:未知错误”。
[谁能帮我解决这个问题?谢谢!
而且任何人都可以告诉我,如何在单独的Text(而不是列表!)中显示该JSON文件的特定值!再次感谢!
这是代码:
import SwiftUI
struct Response: Codable {
var countries: [Result]
}
struct Result: Codable {
let id = UUID()
var Country: String
var TotalConfirmed: Int
var TotalDeaths: Int
}
struct ExampleCorona: View {
@State private var countries = [Result]()
var body: some View {
List(countries, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.Country)
.font(.headline)
Text("\(item.TotalConfirmed)")
}
}.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://api.covid19api.com/summary") 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.countries = decodedResponse.countries
}
// 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()
}
}
如果JSON密钥的数量不等于您必须指定CodingKeys
的结构成员的数量,则您要解码的那些密钥
struct Result: Codable {
let id = UUID()
let country : String
let totalConfirmed : Int
let totalDeaths : Int
private enum CodingKeys: String, CodingKey {
case country = "Country"
case totalConfirmed = "TotalConfirmed"
case totalDeaths = "TotalDeaths"
}
}