【问题标题】:access json with the rapidapi provided nsurlsession [duplicate]使用提供 nsurlsession 的 rapidapi 访问 json [重复]
【发布时间】:2020-03-18 23:44:32
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 Stackoverflow。请搜索。如何解析 JSON 是最常见的问题之一。这里有很多related questions

标签: swift api nsurlsession rapidapi


【解决方案1】:

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

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

查看这个问题了解更多详情:Correctly Parsing JSON in Swift 3

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多