我正在尝试从Swift 5中的OpenWeatherMap API解析数据,但是我不确定为什么在天气状况下,对于description和icon的两个值它返回null。我可以接收日期值,并且可以在控制台中打印整个JSON对象。谁能帮忙?
"list": [
{
"dt": 1485799200,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "02n"
}
],
"wind": {
"speed": 4.77,
"deg": 232.505
},
"dt_txt": "2017-01-30 18:00:00"
},
class WeatherForecast {
var _description : String?
var _icon : String?
var _date: String?
init(weatherDict: Dictionary<String, Any>){
if let weather = weatherDict["weather"] as? Dictionary<String, Any>{
if let desc = weather["description"] as? String{
self._description = desc
}
if let icon = weather["icon"] as? String{
self._icon = icon
}
}
if let rdate = weatherDict["dt_txt"] as? String{
self._date = rdate
}
}
}
然后在我的viewcontroller上:
func getWeatherData(cityName: String){
let url = URL(string: "http://api.openweathermap.org/data/2.5/forecast?q=\(cityName)&appid=**********")!
AF.request(url).responseJSON{(response) in
let result = response.result
switch result {
case.success(let value): print(value)
if let dictionary = value as? Dictionary<String, AnyObject>{
if let list = dictionary["list"] as? [Dictionary<String, AnyObject>]{
for item in list{
let forcast = WeatherForecast(weatherDict: item)
self.weatherForcasts.append(forcast)
}
print(self.weatherForcasts.count)
self.weatherTableView.reloadData()
}
}
case.failure(let error): print(error)
}
}
}
原因是您的天气不是字典。它是一个数组。因此,您需要先获取数组然后再获取字典。
if let weather = (weatherDict["weather"] as? Array ?? [])[0] as? Dictionary<String, Any>{
if let desc = weather["description"] as? String{
self._description = desc
}
if let icon = weather["icon"] as? String{
self._icon = icon
}
}
if let rdate = weatherDict["dt_txt"] as? String{
self._date = rdate
}