OpenWeatherMap and Swift 4

六月ゝ 毕业季﹏ 提交于 2019-12-13 03:42:22

问题


I am trying to build a simple weather app using OpenWeatherMap APIs in Swift 4. I can parse Json data in simple cases, but this one has a more complex structure.

This is the Json file the API returns.

{"coord":{"lon":144.96,"lat":-37.81},"weather":[{"id":520,"main":"Rain","description":"light intensity shower rain","icon":"09n"}],"base":"stations","main":{"temp":288.82,"pressure":1019,"humidity":100,"temp_min":288.15,"temp_max":289.15},"visibility":10000,"wind":{"speed":4.1,"deg":200},"clouds":{"all":90},"dt":1544284800,"sys":{"type":1,"id":9548,"message":0.5221,"country":"AU","sunrise":1544208677,"sunset":1544261597},"id":2158177,"name":"Melbourne","cod":200}

I created a few Struct(s) to get the Json data.

struct CurrentLocalWeather: Decodable {
    let base: String
    let clouds: Clouds
    let cod: Int
    let coord: Coord
    let dt: Int
    let id: Int
    let main: Main
    let name: String
    let sys: Sys
    let visibility: Int
    let weather: [Weather]
    let wind: Wind
}
struct Clouds: Decodable {
    let all: Int
}
struct Coord: Decodable {
    let lat: Double
    let lon: Double
}
struct Main: Decodable {
    let humidity: Int
    let pressure: Int
    let temp: Double
    let tempMax: Int
    let tempMin: Int
    private enum CodingKeys: String, CodingKey {
        case humidity, pressure, temp, tempMax = "temp_max", tempMin = "temp_min"
    }
}
struct Sys: Decodable {
    let country: String
    let id: Int
    let message: Double
    let sunrise: UInt64
    let sunset: UInt64
    let type: Int
}
struct Weather: Decodable {
    let description: String
    let icon: String
    let id: Int
    let main: String
}
struct Wind: Decodable {
    let deg: Int
    let speed: Double
}

To use those datas this is the code I wrote:

let url = "https://api.openweathermap.org/data/2.5/weather?q=melbourne&APPID=XXXXXXXXXXXXXXXX"
        let objurl = URL(string: url)

        URLSession.shared.dataTask(with: objurl!) {(data, response, error) in

            do {
                let forecast = try JSONDecoder().decode([CurrentLocalWeather].self, from: data!)
                for weather in forecast {
                    print(weather.name)
                }
            } catch {
                print("Error")
            }

        }.resume()

That should print the city name in the console. Unfortunately it prints Error.


回答1:


You need

let forecast = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
print(forcast.name)

as the root is a dictionary not array



来源:https://stackoverflow.com/questions/53687617/openweathermap-and-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!