ios - IOS Swift - API fetch(能够在控制台日志中获取数据,但无法显示)
问题描述
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var data = [WeatherResponse]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Værmelding"
downloadJson {
self.tableView.reloadData()
}
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = data[indexPath.row].geometry.type.capitalized
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DetailViewController {
destination.data_detail = data[(tableView.indexPathForSelectedRow?.row)!]
}
}
func downloadJson(completed: @escaping () -> ()) {
let jsonUrlString = "https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=60.10&lon=9.58"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
print("checking for data")
if err == nil {
do {
let weather = try JSONDecoder().decode(WeatherResponse.self, from: data!)
print(weather)
DispatchQueue.main.async {
completed()
}
} catch let jsonErr {
print(jsonErr, "is error")
}
}
}.resume()
}
}
import Foundation
struct WeatherResponse:可解码 { 让几何:天气让属性:属性让类型:字符串
}
// MARK: - Geometry
struct Weather: Decodable {
let type: String
let coordinates: Array<Double>
}
//MARK: - Properties
struct Properties: Decodable {
let meta: Meta
//let timeseries: [Timesery]
}
//MARK: - Meta
struct Meta: Decodable {
let updated_at: String
let units: Units
}
// MARK: - Units
struct Units: Decodable {
let air_pressure_at_sea_level: String
let air_temperature: String
let cloud_area_fraction: String
let precipitation_amount: String
let relative_humidity: String
let wind_from_direction: String
let wind_speed: String
}
当我将 API 作为数组获取时,该代码有效,但在这里它不显示。这可能是因为它试图从字典中读取数据。当我从 API 获取时,代码工作正常,例如:Dota、JSON 虚拟数据和使用 id 的 api。
解决方案
推荐阅读
- laravel - 在 MariaDB 上使用 JSON 字段时出现迁移错误
- python - _tkinter.TclError: bad window path name ".!toplevel" 使关闭按钮退出窗口而不出错
- python - Bash脚本到Python不知道如何
- java - 单击android上的手机硬件后退按钮时从未调用过onResume?
- python - 使用 PyQt5 提取网页的某些部分并显示它们
- javascript - Firebase 数据库数据检索遇到问题
- reactjs - React:componentDidUpdate - 当我更新数组中的对象时,以前的状态与当前状态相同
- drupal - Drupal JSON:API 核心模块。无法使用授权
- javascript - Javascript根据另一个元素提取数组中的元素
- r - R: data.table 同时对多个数据集进行子集化