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. 是不是很簡單?!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章