API 调用和 JSON 解码工作正常,因为我可以毫无问题地打印以控制 JSON 数据集中的任何项目。
这是 API 调用和测试打印:
import Foundation
import SwiftUI
import Combine
class APICall : ObservableObject {
@Published var summary: Summary?
init () {
pullSummary()
}
func pullSummary() {
let urlCall = URL(string: "https://api.covid19api.com/summary")
guard urlCall != nil else {
print("Error reaching API")
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: urlCall!) { (data, response, error) in
if error == nil && data != nil {
let decoder = JSONDecoder()
do {
let summary = try decoder.decode(Summary.self, from: data!)
print(summary.byCountry[40].cntry as Any)
DispatchQueue.main.async {
self.summary = summary
}
}
catch {
print("Server busy, try again in 5 min.")
}
}
}
dataTask.resume()
}
}
这是用于解码和数据对象结构的“摘要”数据模型的结构:
import Foundation
struct Summary: Decodable {
let global: Global
let byCountry: [ByCountry]
let date: String
enum CodingKeys: String, CodingKey {
case global = "Global"
case byCountry = "Countries"
case date = "Date"
}
struct Global: Decodable {
let globalNC: Int
let globalTC: Int
let globalND: Int
let globalTD: Int
let globalNR: Int
let globalTR: Int
enum CodingKeys: String, CodingKey {
case globalNC = "NewConfirmed"
case globalTC = "TotalConfirmed"
case globalND = "NewDeaths"
case globalTD = "TotalDeaths"
case globalNR = "NewRecovered"
case globalTR = "TotalRecovered"
}
}
struct ByCountry: Decodable {
let cntry: String?
let ccode: String
let slug: String
let cntryNC: Int
let cntryTC: Int
let cntryND: Int
let cntryTD: Int
let cntryNR: Int
let cntryTR: Int
let date: String
enum CodingKeys: String, CodingKey {
case cntry = "Country"
case ccode = "CountryCode"
case slug = "Slug"
case cntryNC = "NewConfirmed"
case cntryTC = "TotalConfirmed"
case cntryND = "NewDeaths"
case cntryTD = "TotalDeaths"
case cntryNR = "NewRecovered"
case cntryTR = "TotalRecovered"
case date = "Date"
}
}
}
如图所示,API 调用和 JSON 解码的结果根据需要使用 ObserveableObject 和 @Published 发布。
在 ContentView 中,我遵循 ObservedObject 规则,只想在 UI 上显示来自 JSON 数据的数据点以确认它正在工作:
import SwiftUI
import Foundation
import Combine
struct ContentView: View {
@ObservedObject var summary = APICall()
var body: some View {
Text($summary.date)
.onAppear {
self.summary.pullSummary()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
但是...我在文本显示行 1)Initializer 'init(_:)' requires that 'Binding<Subject>' conform to 'StringProtocol'
和 2)处收到这 2 个错误Value of type 'ObservedObject<APICall>.Wrapper' has no dynamic member 'date' using the key path from root type 'APICall'
。
我猜第二个错误是问题的根本原因,表明数据没有正确传递到 ContentView 中。
我很感激任何建议。
谢谢。