OpenWeatherMap和Swift 4 [英] OpenWeatherMap and Swift 4
问题描述
我正在尝试在Swift 4中使用OpenWeatherMap API构建一个简单的气象应用程序. 我可以在简单的情况下解析Json数据,但是这个结构更复杂.
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.
这是API返回的Json文件.
This is the Json file the API returns.
{"coord":{"lon":144.96,"lat":-37.81},"weather":[{"id":520,"main":"Rain","description":"light 强度阵雨 雨","icon":"09n"}],基本":站点",主":{温度":288.82,压力":1019,湿度":100,温度_分钟":288.15, "temp_max":289.15},可见性":10000,风":{速度":4.1,度":200},云":{全部":90},"dt":1544284800,"sys:{" type:1," id:9548," message:0.5221," country:" AU," sunrise:1544208677," sunset:1544261597}," id:2158177," name:" Melbourne," cod:200}
{"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}
我创建了一些Struct来获取Json数据.
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.
推荐答案
您需要
let forecast = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
print(forcast.name)
因为根是字典而不是数组
as the root is a dictionary not array
这篇关于OpenWeatherMap和Swift 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!