刷新令牌uber swift返回nil

时间:2017-02-21 18:47:30

标签: ios swift uber-api

我正在尝试在我的项目中与uber进行身份验证,转到uber本机应用程序然后返回我的应用程序的路径是可以的。但是,它只返回TokenString和ExpirationDate,而refreshToken返回为nil。

这是我的代码

AuthorizationBaseViewController

 class AuthorizationBaseViewController: UIViewController {

    func delay(delay: Double, closure: ()->()) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay*Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
    }

    func showMessage(message: String) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        let okayAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
        alert.addAction(okayAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }

    func checkError(response: Response) {
        // Unauthorized
        if response.statusCode == 401 {
            TokenManager.deleteToken()
            dispatch_async(dispatch_get_main_queue(), {
                self.reset()
            })
        }
    }

    func reset() {

    }

    // Mark: LoginButtonDelegate

    func loginButton(button: LoginButton, didLogoutWithSuccess success: Bool) {
        if success {
            showMessage(NSLocalizedString("Integration with uber canceled.", comment: ""))
        }
    }

    func loginButton(button: LoginButton, didCompleteLoginWithToken accessToken: AccessToken?, error: NSError?) {
        if let _ = accessToken {


            print(accessToken?.tokenString)
            print(accessToken?.expirationDate)
            print(accessToken?.refreshToken)

            showMessage(NSLocalizedString("Uber user authenticated successfully.", comment: ""))
            if let url = NSURL(string: "xxxxxxxxxxxxxx") {
                let request = NSMutableURLRequest(URL: url)
                request.HTTPMethod = "POST"
                request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
                let token = AccessToken?()
                let jsonObject = ["token" : (token?.tokenString)!, "refresh_token" : (token?.refreshToken)!,"expires_in" : (token?.expirationDate)!, "user_id" : "uber_uuid"  , "token_type" : "Bearer"] as Dictionary <String,AnyObject>

                request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: [])

                NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
                    guard
                        let data = data where
                        error == nil &&
                            (response as? NSHTTPURLResponse)?.statusCode == 200
                        else {
                            print((response as? NSHTTPURLResponse)?.statusCode ?? "no status code")
                            print(error?.localizedDescription ?? "no error description")
                            return
                    }
                    print(String(data: data, encoding: NSUTF8StringEncoding) ?? "no string from data")
                    }.resume()
            }
            showMessage((error?.localizedDescription)!)



        } else if let error = error {
            showMessage(error.localizedDescription)
        } else {
            showMessage("Error")
        }
    }
}

LoginViewController

    class ImplicitGrantLoginViewController: AuthorizationBaseViewController, LoginButtonDelegate {


    /// The LoginManager to use for login
    let loginManager = LoginManager(loginType: .Native)

    /// The RidesClient to use for endpoints
    let ridesClient = RidesClient()

    // The Uber button to use for UI

    var uberLoginButton: LoginButton?

    // The Uber Scopes

    var uberScopes: [RidesScope]?

    @IBOutlet weak var logoutBgView: UIView!


    override func viewDidLoad() {
        super.viewDidLoad()

        //UberScopes to get authentication

        uberScopes = [.History, .Profile, .HistoryLite,.Places, .RideWidgets]

        uberLoginButton = LoginButton(frame: CGRectZero,scopes:uberScopes! ,loginManager: loginManager)


        // Uber Login Button Creation

        let loginButton = LoginButton(frame: CGRectZero, scopes: uberScopes!, loginManager: loginManager)
        loginButton.presentingViewController = self
        loginButton.delegate = self
        loginButton.frame = logoutBgView.bounds
        loginButton.autoresizingMask =
            [.FlexibleWidth, .FlexibleHeight]
        logoutBgView.addSubview(loginButton)


   }

基本上,如果刷新令牌返回到我的应用程序,则会发出POST请求以及TokenString和ExpirationDate

验证完成后,在显示授权视图之前,会出现以下错误

  

MyApp [18136:615342] -canOpenURL:网址失败:“uberauth:// connect?third_party_app_name = MyApp&amp; callback_uri_string = xxxxxx&amp; client_id = xxxxxxxxxx&amp; login_type = default&amp; scope = history%20profile%20history_lite% 20places%20ride_widgets&安培; SDK = IOS&安培; sdk_version = 0.6.0

即使出现此错误,也会显示授权范围的屏幕,当我点击“允许”时,我会看到调试区域中的返回,但是由于refreshtoken的应用程序崩溃是nil而HTTP请求没有收到它。

l 由于refreshtoken导致App崩溃时出错

我已经检查了plist文件,并根据uber文档/ github存储库填充。回调URI,LSApplicationQuerieScheme,客户端ID,DisplayName是正确的。

1 个答案:

答案 0 :(得分:1)

因此,通过阅读您的问题,我会看到一些问题。看起来您正试图通过Uber应用程序进行Native登录,该应用程序应该返回访问令牌和刷新令牌。如果您没有Native登录,那么您将无法获得刷新令牌,这就是它为零的原因。

您列出的错误消息:

  

MyApp [18136:615342] -canOpenURL:网址失败:   ?&#34; uberauth://连接third_party_app_name = MyApp的   &amp; callback_uri_string = xxxxxx&amp; client_id = xxxxxxxxxx   &安培;的login_type =默认&安培;范围=历史%20profile%20history_lite%20places%20ride_widgets&安培; SDK = IOS&安培; sdk_version = 0.6.0

表示您尚未将uberauth添加到LSApplicationQueriesSchemes下的应用的plist中。我注意到你把它称为LSApplicationQuerieScheme拼写错误。那可能是你的问题。

您说授权代码屏幕仍然显示,这让我觉得它在网页浏览中会回退到Implicit Grant,而不会向您返回刷新令牌。

此外,在您提出发布请求的代码中,您永远不会使用您获得的访问令牌:

let token = AccessToken?()
let jsonObject = ["token" : (token?.tokenString)!,
                  "refresh_token" : (token?.refreshToken)!,
                  "expires_in" : (token?.expirationDate)!, 
                  "user_id" : "uber_uuid"  , 
                  "token_type" : "Bearer"] as Dictionary <String,AnyObject>

您初始化一个新的空AccessToken,然后强制在该令牌上打开几个可选值(您从初始登录中获得的值)。因此,这些值几乎肯定是零,并且力展开导致崩溃