ios - 无法让 JSON Structs 工作 Swift 4
问题描述
我正在尝试在 Swift 4 中使用 OpenWeatherMap API 制作天气应用程序,我想获得 5 天的预报。到目前为止,我有一个使用 Openweathermaps 不同的 API,使用相同的方法和结构的完全可用的应用程序。但是当我为我的新 ViewController 制作一堆新结构时,它会在屏幕上填满多个错误,例如:'Type 'MyForecast' does not conform to protocol 'Decodable'' and: ''Sys' is ambiguous for在此上下文中键入查找'和:''Sys'的重新声明无效'。
提前致谢。
下面的代码:
结构:
import UIKit
import Foundation
//JSON Structs below
struct Coordinate : Decodable {
let lat, lon : Double?
}
struct Weather: Decodable {
var id : Int?
var main, description, icon : String?
}
struct Sys: Decodable {
let pod: Bool?
}
struct Main: Decodable {
let temp, temp_min, temp_max, sea_level, grnd_level, temp_kf : Double?
let pressure, humidity : Int?
}
struct Wind: Decodable {
let speed : Double?
let deg: Int?
}
struct Clouds: Decodable {
let all: String?
}
struct MyForecast : Decodable {
let cod, dnt: Int?
let message : Double?
let name : String?
let coord : Coordinate?
let id : Int?
let sys : Sys?
let main: Main?
let wind: Wind?
let weather: [Weather]?
let clouds: Clouds?
}
查看控制器代码:
class ForecastViewController: UIViewController {
@IBOutlet weak var testLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func loadWeather() {
guard let APIUrl = URL (string: "http://api.openweathermap.org/data/2.5/forecast?q=Crowland,uk&APPID=***API***KEY***&units=metric") else { return }
//API KEY
URLSession.shared.dataTask(with: APIUrl) { data, response, error in
guard let data = data else { return }
let decoder = JSONDecoder()
//Decoder
do {
let weatherData = try decoder.decode(MyForecast.self, from: data)
if (self.testLabel != nil)
{
if let test = (weatherData.weather?.first?.main) { //using .first because Weather is stored in an array
print(test)
DispatchQueue.main.async {
self.testLabel.text! = String (test)
}
}
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
}
解决方案
推荐阅读
- for-loop - Julia,for循环迭代器增加到零
- macos - 如何在 Mac OS 上安装 wget
- reactjs - 如何在 React 中为 axios 设置正确的测试?
- python - 模型预测常数
- java - 我要apk先打开第二页
- python - 如何在python函数中添加数学函数作为参数
- amazon-web-services - 在 Elastic Beanstalk 中部署时无法在配置文件之间切换
- sql-server - 案例语句 SQL Server 中的 OR 条件
- aem - 在 HTL/Sightly 中是否可以有条件地打开或关闭标签?
- javascript - 在 Vue 中加载数据后自动调整 textarea 的大小