【发布时间】:2021-02-11 05:36:00
【问题描述】:
我正在创建这个“天气应用”
我是 swift 新手,我对 API 的了解更少。
我想我能够从 [1]:https://api.met.no/weatherapi/locationforecast/2.0/documentation%23!/data/get_compact#!/data/get_compact_format API,但它显示在控制台窗口中,而我基本上试图让它出现在我的 UItableview 单元格中。
谁能帮忙?
这是我的 viewController.swift 文件:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let data = ["Nå", "Neste time", "Neste 6 timer", "Neste 12 timer"]
let subtitles = ["Temperatur:", "Vær:", "Vær:", "Vær:"]
struct WeatherManager: Codable {
let air_temperature: Int
let next_1_hours: Int
let next_6_hours: Int
let next_12_hours: String
}
override func viewDidLoad() {
super.viewDidLoad()
metAPI.shared.fetchWeatherManager()
tableView.delegate = self
tableView.dataSource = self
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped me")
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
cell.detailTextLabel?.text = subtitles[indexPath.row]
return cell
}
}
这是我的 weatherManager.swift 文件:
final class metAPI {
static let shared = metAPI()
func fetchWeatherManager() {
let url = URL(string: "https://api.met.no/weatherapi/locationforecast/2.0/compact.json?lat=10.74481&lon=59.91116")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
/*let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
print("data was nil")
return
}
guard (try? JSONDecoder().decode(WeatherManager.self, from: data)) != nil else {
print("couldnt decode json")
return
}
}
task.resume()
}*/
}
struct WeatherManager: Codable {
let air_temperature: Int
let next_1_hours: Int
let next_6_hours: Int
let next_12_hours: String
}
}
我希望在每个单元格的右侧显示不同的数据,所以:
air_temperature: Int, 10 度 next_1_hours: Int, Rain 4mm next_6_hours:Int,多云 3mm next_12_hours:字符串,太阳
如果有人可以帮助我一点吗? :)
【问题讨论】:
-
有两个主要问题:JSON 似乎与数据模型不匹配,您根本没有使用解码后的数据。此外,不要忽略
try?的错误。添加一个 do catch 块并打印错误。
标签: ios swift api uitableview