demoEdisonswift3.0

swift微博第12天(OAuth授权)

2017-08-20  本文已影响64人  IIronMan
1.基本概念
2.OAuth 授权流程图
**OAuth授权流程**
3.注册应用程序

授权请求地址https://api.weibo.com/oauth2/authorize?client_id=2202957917&redirect_uri=http://www.jianshu.com/u/8fed18ed70c9

获取未授权的RequestToken

注意:

 - 1.不能有多余的空格  否则报: `(error:invalid_client)`
 - 2.如果`APP key`不对也会报: `(error:invalid_client)` 
 -  3.如果`url`不对也会报错  `(error:redirect_uri_mismatch)`

4.跳转进入授权的控制器

import UIKit
class OAuthViewController: UIViewController {
// 全局变量
let appKey = "2202957917"
let appSecret = "f482e170b0d6eae93b4abdfff285a9c8"
let redirect_uri = "http://www.jianshu.com/u/8fed18ed70c9"

override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = UIColor.red
    
    view.addSubview(webView)
    
    navigationItem.title = "安其拉之路";
    navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthViewController.click))

    // 1.获取未授权的RequestToken  要求 SSL 1.2版本
    let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
    let url = NSURL(string: urlStr)
    let request = NSURLRequest(url: url! as URL)
    webView.loadRequest(request as URLRequest)
    
}

private lazy var webView: UIWebView = {

    let webview = UIWebView(frame: CGRect(x: 0, y: 0, width: JKscreenW, height: JKscreenH))
    webview.delegate = self
    return webview

    }()

func click(){
    
    dismiss(animated: true, completion: nil)
    
   }
}

extension OAuthViewController: UIWebViewDelegate{

// 返回 true正常加载  false不加载
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{

    /*
     加载授权界面
     https://api.weibo.com/oauth2/authorize?client_id=2202957917&redirect_uri=http://www.jianshu.com/u/8fed18ed70c9
    
     跳转到授权界面 
     https://api.weibo.com/oauth2/authorize
    
     授权成功
     http://www.jianshu.com/u/8fed18ed70c9?code=ed9df4b69d51158ad03d15a72ea8fa65
    
     取消授权
     http://www.jianshu.com/u/8fed18ed70c9?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
    */
    
    print(request.url!.absoluteString)
    
    // 1.如果不是授权回调页,就继续加载
    if !request.url!.absoluteString.hasPrefix(redirect_uri) {
        
        // 继续加载
        return true
    }
    
    // 2.判断是否授权成功
    let codeStr = "code="
    if request.url!.query!.hasPrefix(codeStr) {
        
        // 授权成功
        print("授权成功")
        let code = request.url!.query?.substring(from: codeStr.endIndex)
        print(code!)
        
    }else{
    
        // 取消授权
        print("取消授权")
    }
      return true
    }
 }

5.利用授权的RequestToken 来换取AccessToken

利用授权的RequestToken 来换取AccessToken
/*
 * 换取AccessToken
 * :param: code 已经授权的 RequestToken
 */
private func loadAccessToken(code: String){

   // 1.定义路径
    let path = "oauth2/access_token"
   // 2.封装参数
    let params = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]

    NetworkTools.shareNetworkTools().post(path, parameters: params, progress: nil, success: { (
        _, JSON) in
        
        print(JSON!)
        
    }) { (_, error) in
       
        print(error)
        
    }
    
    
    print(path)
}

// 说明你要自己写一个网络的封装NetworkTools.swift

import UIKit

import AFNetworking

class NetworkTools: AFHTTPSessionManager {

static let tools: NetworkTools = {

    // 注意: baseURL一定要以 / 结尾
    let url = NSURL(string: "https://api.weibo.com/")
    let t = NetworkTools(baseURL: url! as URL)
    t.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript","text/plain") as? Set<String>
    return t

}()

// 获取单粒方法
class func shareNetworkTools() -> NetworkTools {
    
    return tools
   }
}
单粒式的网络工具
上一篇下一篇

猜你喜欢

热点阅读