【发布时间】:2020-04-18 09:08:29
【问题描述】:
我正在尝试向 openweathermap.org 的 API 发出异步 API 获取请求。结果应该是这个JSON structure。我特别想得到温度。我被教导通过将 JSON 包装到字典中来使用它。问题是我不知道我可以用什么来指定对象“main”(在 JSON 中)并获取温度。我必须逐个对象迭代吗?这是我到目前为止的代码(旁注:我的应用程序使用 50 mb 的 RAM 是否令人担忧?)
let url = URL(string: stringURL)
let myQ = DispatchQueue.init(label: "getCityDetails")
myQ.async {
let session = URLSession.shared
let m = session.dataTask(with: url!, completionHandler: {(data, response, error) in
if let error = error {
print(error.localizedDescription)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Error with the response, unexpected status code: \(String(describing: response))")
return
}
do {
if let d = data{
let dictionaryObj = try JSONSerialization.jsonObject(with: d, options: []) as! NSDictionary
print(dictionaryObj)
}
}catch{
print(error.localizedDescription)
}
})
m.resume()
【问题讨论】:
-
尝试编译您附加到答案的代码:)