Swift(八):完成Sina授权,获取accessToken

公共文件定义 Sina 的分发的 key

//
//  Global.swift
//  swift-AFNetworking
//
//  Created by HMC on 16/8/10.
//  Copyright © 2016年 SKing. All rights reserved.
//

import Foundation

let AppKey = "2259417197"
let AppSecret = "d46412dd47e35a075a645d33618a8007"
let redirect_uri = "http://www.jianshu.com"

授权页加载,所用的网络请求已经在上一篇笔记中完成,不懂请查看.

//
//  AuthViewController.swift
//  swift-AFNetworking
//
//  Created by HMC on 16/8/10.
//  Copyright © 2016年 SKing. All rights reserved.
//

import UIKit
import SVProgressHUD

class AuthViewController: UIViewController {
    
    @IBOutlet weak var webV: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置 navigationController
        setNav()
        //加载 webview 的授权
        authorToSina(AppKey, appURL: redirect_uri)
        
    }

}
// MARK: - 控制器NavigationController的设置
extension AuthViewController {
    
    private func setNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(back))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: .Plain, target: self, action: #selector(autoLogin))
        
    }
    //返回
    func back() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动登录
    func autoLogin() {
        //思路:注入 js 代码到 webView
        let jsString = "document.getElementById('userId').value='15225124020';document.getElementById('passwd').value='自己账户的密码';"
        webV.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    
    func authorToSina(appkey:String,appURL:String) {
        
        webV.loadRequest(NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(appURL)")!))
        
    }
}


//MARK:- webView 代理
extension AuthViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    //
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            
            return true
        }
        guard url.absoluteString.containsString("code=")else {
            
            return true
        }
        
        let separateArray = url.absoluteString.componentsSeparatedByString("code=")
        //获取 code
        let code = separateArray.last
        getAccessToken(code!)
        print(code)
        return false
        
    }
    
}

// MARK: - 用sina 返回的 code 获取 accessToken
extension AuthViewController {

    private func getAccessToken(code : String) {
        
        let staticURL = "https://api.weibo.com/oauth2/access_token"
        //"grant_type":"authorization_code" 固定写法
        let parameters = ["client_id":AppKey, "client_secret":AppSecret, "grant_type":"authorization_code", "redirect_uri":redirect_uri, "code":code]
        AFNetworkingManager.shareObject.requestData(.POST, urlString: staticURL, parameters: parameters) { (result, error) in
            
            print(result)
            
        }
    }
}

你可能感兴趣的:(Swift(八):完成Sina授权,获取accessToken)