我正在尝试在我的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。我还是个新手,希望你能帮上忙。
发布于 2021-09-20 08:52:40
您需要解析响应。JSONSerialization类方法jsonObject(with:options:)返回一个Any类型的值,如果数据无法解析,它将抛出一个错误。
let json = try? JSONSerialization.jsonObject(with: data, options: [])
有关更多详细信息,请查看此问题:Correctly Parsing JSON in Swift 3
另外,我不是Swift专家,但我是来帮助你的。
https://stackoverflow.com/questions/59002091
复制相似问题