从 NSURLSession(Lyft API)访问 JSON 响应中的键值时出现问题

问题描述 投票:0回答:1

我正在使用新的 Lyft API,在“身份验证”部分中,它表示发送访问令牌请求并显示示例响应,其中包含名为“access_token”的密钥。

回复示例

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token": <access_token>,
"token_type":"bearer",
"expires_in":3600,
"scope": "public"
}

然而,当我拨打电话时(是的,ClientID 和 Secret 是正确的,但我无法在此处发布它们),它会返回响应,但访问令牌为零。

感谢您一如既往的帮助!文档链接如下,

API 文档,

https://developer.lyft.com/docs/authentication

func authorize() {

    let authString = NSString(format: "%@:@%", clientID, clientSecret)
    let authData = authString.dataUsingEncoding(NSUTF8StringEncoding)

    let base64String = authData!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

    let url = NSURL(string: "https://api.lyft.com/oauth/token")
    let request = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "GET"
    request.setValue("Basic \(base64String)", forHTTPHeaderField: "Authorization")

    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

    let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        let dictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)


        if let accessToken : String = dictionary["access_token"] as? String {

            print(accessToken)
        }
    }

    task.resume()

}
ios swift swift2 nsurlsession nsjsonserialization
1个回答
0
投票

根据 Lyft 文档,我认为您的身份验证字符串的格式是错误的。

我认为你应该这样做

let authString = NSString(format: "%@:@%", clientID, clientSecret)
,不是

let authString = NSString(format: "%@, @%", clientID, clientSecret)

© www.soinside.com 2019 - 2024. All rights reserved.