1

我正在尝试在我的 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。我对此还是很陌生,希望您能提供帮助。

4

1 回答 1

0

您需要解析响应。该类JSONSerialization方法jsonObject(with:options:)返回一个 Any 类型的值,如果无法解析数据,则会引发错误。

let json = try? JSONSerialization.jsonObject(with: data, options: [])

查看此问题以了解更多详细信息:正确解析 Swift 3 中的 JSON

PS 我不是 Swift 专家,但在这里为您提供帮助。

于 2021-09-20T08:52:39.917 回答