【发布时间】:2020-07-03 13:19:07
【问题描述】:
我正在尝试从这个庞大的 JSON 数组中解码数据 https://coronavirus-19-api.herokuapp.com/countries 我已经幸运地按国家/地区解码或使用全球总统计数据 https://coronavirus-19-api.herokuapp.com/all 通过执行以下操作
//
// GlobalSwiftViewController.swift
// Universal
//
// Created by JOE on 3/20/20.
import UIKit
final class StatSwiftViewController: UIViewController {
// THESE LABELS WILL RETRIEVE THE FOLLOWING DATA FROM THE URL: THE CASE , DEATH AND RECOVERED DATA
@IBOutlet weak var CaseLable: UILabel!
@IBOutlet weak var DeathLable: UILabel!
@IBOutlet weak var RecoveredLabel: UILabel!
struct JSONTest: Decodable {
let cases: Double
let deaths: Float
let recovered: Int?
}
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://coronavirus-19-api.herokuapp.com/all"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
//Decode data
let urlString = try JSONDecoder().decode(JSONTest.self, from: data)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
//HERE WE ARE SHOWING TO THE USER THE DATA FROM THE URL ABOVE
DispatchQueue.main.async {
self.CaseLable.text = numberFormatter.string(for: urlString.cases)
self.DeathLable.text = numberFormatter.string(for: urlString.deaths)
self.RecoveredLabel.text = numberFormatter.string(for: urlString.recovered)
//self.timeLabel.text = JSONTest.deaths
}
} catch let jsonError {
print(jsonError)
}
}.resume()
}
}
现在我正在尝试解码此 URL https://coronavirus-19-api.herokuapp.com/countries 中的所有数据以显示在一个视图控制器中,我已经通过使用单个 URL https://coronavirus-19-api.herokuapp.com/countries/china 为国家/地区使用上面相同的代码取得了成功添加更多变量和标签但是,我无法通过添加每个国家/地区的每个 URL 或使用所有国家/地区的主 URL https://coronavirus-19-api.herokuapp.com/countries 添加更多县因此,我可以使用 URL 构造所有数组列表适用于所有国家/地区? 注意:我正在尝试编辑/更新上面的代码以在不安装额外 pod 或文件的情况下尽可能获得结果...
【问题讨论】: