首页 > 解决方案 > 无法让 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()

}

}

标签: iosjsonswiftopenweathermap

解决方案


推荐阅读