if let jsonObj = jsonObj as? [String: Any],
let weatherDictionary = jsonObj["weather"] as? [String: Any],
let weather = weatherDictionary["description", default: "clear sky"] as?
NSDictionary {
print("weather")
DispatchQueue.main.async {
self.conditionsLabel.text = "\(weather)"
}
}
// to display weather conditions in "name" from Open Weather
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}]
//No errors, but code is not printing or displaying in App.
答案 0 :(得分:0)
除非您能为上下文提供更多代码,否则我不确定如何帮助解决您的确切问题。然而,
您可以尝试使用Swift 4附带的内置解码。检查出here.基本上,您创建了一个为响应对象建模的类,如下所示:
struct Weather: Decodable {
var id: Int
var main: String
var description: String
var icon: String
}
然后解码它:
let decoder = JSONDecoder()
let weather = try decoder.decode(Weather.self, from: jsonObj)
它会神奇地解码为您需要的数据!如果这不起作用,请告诉我,如果您有更多代码上下文可供我帮助,请发表评论。
答案 1 :(得分:0)
我在此处放置了完整的演示,以展示如何发送HTTP请求并解析JSON响应。
注意:如果您使用HTTP请求而不是HTTPS请求,请配置ATS。
演示网址为" http://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22"。
JSON格式如下,演示了如何获取城市名称。
{
cod: "200",
message: 0.0032,
cnt: 36,
list: [...],
city: {
id: 6940463,
name: "Altstadt",
coord: {
lat: 48.137,
lon: 11.5752
},
country: "none"
}
}
完整演示如下。它显示了如何使用URLSessionDataTask
和JSONSerialization
。
class WeatherManager {
static func sendRequest() {
guard let url = URL(string: "http://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22") else {
return
}
// init dataTask
let dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in
let name = WeatherManager.cityName(fromWeatherData: data)
print(name ?? "")
}
// send the request
dataTask.resume()
}
private static func cityName(fromWeatherData data: Data?) -> String? {
guard let data = data else {
print("data is nil")
return nil
}
do {
// convert Data to JSON object
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
print(jsonObject)
if let jsonObject = jsonObject as? [String: Any],
let cityDic = jsonObject["city"] as? [String: Any],
let name = cityDic["name"] as? String {
return name
} else {
return nil
}
} catch {
print("failed to get json object")
return nil
}
}
}