我正在尝试解析Swift 5中的OpenWeatherMap API中的数据,但我不知道为什么它会返回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
}
}
}然后在我的视图控制器上:
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)
}
}
}发布于 2020-04-10 07:41:25
原因是你的天气,不是一个Dictionary.It,是一个array.So,你需要得到它的数组,然后是字典。
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
}https://stackoverflow.com/questions/61135709
复制相似问题