Issues accessing key value in JSON response from NSURLSession (Lyft API)

时间:2016-02-12 20:02:28

标签: ios api swift2 nsurlsession nsjsonserialization

I'm working with the new Lyft API, in the Authentication section it says to send a request for an access token and shows an example response, with a key called "access_token".

Sample response

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"
}

Yet when I make the call (Yes the ClientID and Secret are correct but I can't post them here) it returns a response but the access token is nil.

Thanks for the help like always! Doc link is below,

API docs,

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()

}

1 个答案:

答案 0 :(得分:0)

Based off the Lyft docs, I think think the format for your auth string is wrong.

I think you should be doing

de(reference(foo)), not

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