zoukankan      html  css  js  c++  java
  • iOS集成丁香园DXY OAuth 登陆 swift代码示例

    问:iOS集成OAuth登陆分几步?

    答:和把大象放冰箱里一样。

    第一步:打开webview,跳转到登陆页面:

            let url = "https://auth.dxy.cn/conn/oauth2/authorize?clientId=xxx&state=xxx&responseType=code&redirectUri=xxx”
            webView.loadRequest(NSURLRequest(URL: NSURL(string:url)!))

    第二步:在AppDelegate中,使用

    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {}方法获取返回的code, 再通过code获取accessToken:

            let requestUrl = NSURL(string: "https://auth.dxy.cn/conn/oauth2/accessToken")
            let postData =  "clientId=xxx&clientSecret=xxx&grantType=authorizationCode&redirectUri=xxx&code=(code)"
             let request = NSMutableURLRequest(URL: requestUrl!)
            request.HTTPMethod = "POST"
            request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)

    第三步:通过accessToken获取用户信息,再捎带把webview关了:

    let getUserInfoRequestUrl = NSURL(string: "https://auth.dxy.cn/conn/oauth2/profile")
    let getUserInfoPostData = "accessToken=(access_token)"
                                
    let getUserInfoRequest = NSMutableURLRequest(URL: getUserInfoRequestUrl!)
    getUserInfoRequest.HTTPMethod = "POST"
    getUserInfoRequest.HTTPBody = getUserInfoPostData.dataUsingEncoding(NSUTF8StringEncoding)
                            
    let getUserInfoDataTask = session.dataTaskWithRequest(getUserInfoRequest,
                completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
                      if error != nil {
                          print(error?.code)
                          print(error?.description)
                      }
                      else    {
                         let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
                         do{
                            let userInfoResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
                            let id = userInfoResult["id"] as? String
    
                            let viewController = self.window?.rootViewController as! ViewController
                            viewController.id = id
                            viewController.closeWebView()
                         }
                         catch {}
                     }
           })
                                
    getUserInfoDataTask.resume()

    Ok, That's it. 是不是很简单?!

  • 相关阅读:
    Failed to load resource: net::ERR_FILE_NOT_FOUND
    gulp安装详解
    npm install gulp-cli -g时npm ERR! code ECONNREFUSED
    webpack4.43
    修改cmd默认路径
    delphi设置鼠标图形
    Linux常用命令学习
    IO模型介绍 以及同步异步阻塞非阻塞的区别
    TCP的三次握手与四次挥手过程,各个状态名称与含义
    常见的设计模式详解:单例模式、工厂模式、观察者模式
  • 原文地址:https://www.cnblogs.com/zhongzf/p/5064936.html
Copyright © 2011-2022 走看看