我正在尝试在我的 xcode 项目中使用 swift 使用这个天气 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: [])
查看此问题了解更多详细信息:Correctly Parsing JSON in Swift 3
附注我不是 Swift 专家,但可以为您提供帮助。