Swift调用OpenWeather API无法打印或显示天气信息问题排查
解决Swift调用OpenWeather API无数据显示的问题
嘿,我一眼就看出问题所在啦!你这段代码的核心错误是对OpenWeather API返回的weather字段类型判断错了。
先看你给的API返回示例:
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}]
这里的weather是一个包含单个字典的数组,但你的代码里却把它当成了普通字典[String: Any]来解析——这就导致第一步类型转换失败,后面的代码根本没机会执行,自然不会打印或显示任何内容。
修正后的代码
我帮你把代码改好了,你直接用就行:
if let jsonObj = jsonObj as? [String: Any], // 先把weather解析成数组(匹配API返回的类型) let weatherArray = jsonObj["weather"] as? [[String: Any]], // 取数组里的第一个元素(OpenWeather的weather数组通常只有一项) let weatherDict = weatherArray.first, // 取出天气描述字段,设置默认值 let weatherDescription = weatherDict["description"] as? String { print("weather: \(weatherDescription)") DispatchQueue.main.async { self.conditionsLabel.text = weatherDescription } }
调试小技巧
如果之后再遇到类似无报错但无数据的情况,建议拆分判断逻辑并添加错误打印,方便快速定位问题:
if let jsonObj = jsonObj as? [String: Any] { if let weatherArray = jsonObj["weather"] as? [[String: Any]] { if let weatherDict = weatherArray.first { if let weatherDescription = weatherDict["description"] as? String { print("weather: \(weatherDescription)") DispatchQueue.main.async { self.conditionsLabel.text = weatherDescription } } else { print("❌ 无法解析description字段") } } else { print("❌ weather数组为空") } } else { print("❌ weather字段不是数组类型") } } else { print("❌ jsonObj不是预期的字典类型") }
内容的提问来源于stack exchange,提问作者Rich J
相关产品推荐
相关产品推荐

