我正在尝试使用 swift 在我的 xcode 项目中使用此天气 api https://rapidapi.com/interzoid/api/us-weather-by-zip-code/endpoints。他们为我提供了代码
import Foundation
let headers = [
"x-rapidapi-host": "us-weather-by-zip-code.p.rapidapi.com",
"x-rapidapi-key": "my api key"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://us-weather-by-zip-code.p.rapidapi.com/getweatherzipcode?zip=11214")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
运行它后,我得到了响应标头,但我希望得到响应正文,即 json。我对此还很陌生,希望你能提供帮助。
您需要解析响应。JSONSerialization
类方法jsonObject(with:options:)
返回 Any 类型的值,如果无法分析数据,则会引发错误。
let json = try? JSONSerialization.jsonObject(with: data, options: [])
查看此问题以获取更多详细信息:在 Swift 3 中正确解析 JSON
附言我不是 Swift 专家,但在这里为您提供帮助。