【问题标题】:SwiftyJSON : How can I add token?SwiftyJSON:如何添加令牌?
【发布时间】:2016-06-23 01:17:33
【问题描述】:

我正在使用 API 并通过 SwiftyJSON 获取 json 数据。我需要为 API 添加令牌。我如何使用SwiftyJson 做到这一点?

我的代码:

让 jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)

    var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)

    let name = readableJSON["standings"]

当我使用 Swift 的 JSON 时,通常我会在这段代码中添加令牌:

    let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
    url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
    url.HTTPMethod = "GET"

【问题讨论】:

    标签: json swift swifty-json


    【解决方案1】:

    您是否正在使用这些数据进行发布/发布?那是有道理的。 我想您已经请求获取“jsonData”包含的可读数据。由于您表明您还没有 json 数据,因此这可能会起作用。

    var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
    url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
    url.HTTPMethod = "GET"
    NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
        if error == nil {
            var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
            let name = readableJSON["standings"]
            url.HTTPBody = try! name.rawData()
            NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
               //do something with his response from getting the data
            })
        } else {
            print(error)
        }
    })
    

    这是一种很老套的做法,但我认为这是你想要的

    【讨论】:

    • 不,我会获取数据。这适用于 GET 吗?抱歉,我现在不在 macbook 上。
    • 技术上是的,虽然我不确定 ios 是如何处理这种事情的:stackoverflow.com/questions/978061/http-get-with-request-body
    • readbleJSON 会用这种方式得到它吗? url 值未在 jsonData 中实现。这是一个问题还是 url 是一样的,他会因为相同的 url 实现而获得令牌? Btw API 正在工作,但它对于实时应用程序是必需的。这段代码也可以工作。
    猜你喜欢
    • 1970-01-01
    • 2011-03-09
    • 2013-07-02
    • 2021-01-17
    • 2018-03-29
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多