刷新超级令牌Swift

时间:2016-03-09 11:00:55

标签: ios swift oauth uber-api

我尝试创建一个集成了优步API的应用。

我可以获取我的oauth令牌,但是当我尝试刷新令牌但API返回401错误时。 我对此端点发出POST请求 https://login.uber.com/oauth/v2/token 有了这个参数:

let params = ["client_secret": ***********, "client_id": ***********, "grant_type": "refresh_token", "redirect_uri": "REDIRECT_URI", "refresh_token": refresh_token]

refresh_token是一个var,它包含我连接用户时Uber API返回的refresh_token键。

任何人都知道如何处理刷新我的令牌?

由于

编辑:

ViewController.swift

UberManager.refreshToken { (changed) -> Void in
    if let change = changed {
        print("token renewable")
    }
}

UberManager.swift

public class UberManager {
    static func refreshToken(completionHandler:(changed: Bool?) -> Void) -> Void {
            Router.RefreshToken().performRequest { (json, error) -> Void in
                if error == nil {
                    print(json)
                }
            }
        }
    }

Router.swift

enum Router: URLRequestConvertible {

    static let baseURL = Constants.APIConstants.api_url
    static let sandboxURL = Constants.APIConstants.sandbox_api
    static let tokenURL = Constants.APIConstants.login_url

    case RefreshToken()

    var method: Alamofire.Method {
        switch self {
        case .RefreshToken():
            return .POST
        }
    }

    var path: String {
        switch self {
        case .RefreshToken():
            return "/v2/token"
        }
    }

    var URLRequest: NSMutableURLRequest {
        var URL = NSURL()
        switch self {
        case .RefreshToken():
            URL = NSURL(string: Router.tokenURL)!
        default:
            // TODO : change this when App is ready
            URL = NSURL(string: Router.sandboxURL)!
        }
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
        mutableURLRequest.HTTPMethod = method.rawValue

        if let token = Session.sessionInfos().access_token {
            mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "authorization")
        }

        switch self {
        case .RefreshToken():
            var params = [String: String]()
            if let refresh_token = Session.sessionInfos().refresh_token {
                params = ["client_secret": Constants.APIConstants.kSecret,
                          "client_id": Constants.APIConstants.kIDClient,
                          "grant_type": "refresh_token",
                          "redirect_uri": Constants.APIConstants.redirect_uri,
                          "refresh_token": refresh_token]
            }

            return ParameterEncoding.URL.encode(mutableURLRequest, parameters: params).0

        }
    }

    func performRequest(completionHandler: (AnyObject?, AppError?) -> Void) {
        request(self).responseData({ (response) -> Void in
            switch response.result {
            case .Failure(let error):
                print("ERROR : \(error.localizedDescription) - \(error.localizedRecoverySuggestion)")
                completionHandler(nil, AppError.Unknown)
                return
            case .Success(_):
                switch response.response!.statusCode {
                case 200, 422:
                    break // wil be handle in responseJSON
                case 401:
                    completionHandler(nil, AppError.AlamofireError)
                case 500:
                    completionHandler(nil, AppError.ServerError)
                default:
                    print("WARNING : status code \(response.response!.statusCode) not handled")
                    completionHandler(nil, AppError.Unknown)
                }
            }

        })
            .responseJSON { (response) -> Void in
            print("\n - request : \(response.request!.HTTPMethod) \(response.request!.URLString)\n\n - has body : \(response.request!.HTTPBody != nil)\n\n - response : \(response.response)\n\n - result : \(response.result)\n")
            switch response.result {
            case .Failure(_):
                completionHandler(nil, AppError.Unknown)
            case .Success(let json):
                if let responseURL = response.response {
                    switch responseURL.statusCode {
                    case 200:
                        completionHandler(json, nil)
                    case 201:
                        completionHandler(json, nil)
                    case 500:
                        completionHandler(nil, AppError.ServerError)
                    default:
                        print(responseURL)
                        print("WARNING : status code \(responseURL.statusCode) not handled")
                        completionHandler(nil, AppError.Unknown)
                    }
                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

从初始响应中提取时,是否确保打开refresh_token值?我自己尝试了这个并在401中传递了一个未包装的可选结果。