1. 新浪开放平台: https://open.weibo.com/
2. 登录新浪账号,微连接 -> 移动应用 -> 立即接入
3. 创建新应用,输入应用名称,选择应用平台,创建
4. 我的应用 -> 选择刚创建的应用 -> 应用信息 -> 高级信息-> OAuth2.0 授权设置 -> 编辑
//网站可随意填写
4.1 授权回调页: https://www.baidu.com
4.2 取消授权回调页: https://www.baidu.com
5.基本信息页得到,APP Key , App Secret 的值
App Key:25******71
//用来识别应用程序
App Secret:97****************************38
6. 键值对应信息
client_id = APP Key
client_secret = App Secret
//OAuth2.0 授权设置
redirect_url = https://www.baidu.com
7. NetworkTools.swift 类 创建接口
import UIKit
import AFNetworking
///请求方法枚举
enum RequestMethod: String {
case GET = "GET"
case POST = "POST"
}
//MARK: - 网络工具
class NetworkTools: AFHTTPSessionManager {
//MARK: - 应用程序信息
private let appKey = 25******71
//用来识别应用程序
private let appSecret = "97****************************38"
//OAuth 2.0 授权设置 同样是用来识别应用程序的
private let redirectUrl = "https://www.baidu.com"
//网络请求完成回调,类似于 OC 的 typeDefine
typealias requestCallBack = (_ result: Any?, _ error: Error?) -> ()
//单例
static let sharedTools:NetworkTools = {
let tools = NetworkTools(baseURL: nil)
//设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set text/html
tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tools
}()
}
extension NetworkTools{
/// oAuth 授权 URL
/// - see: [https://open.weibo.com/wiki/Oauth2/authorize](https://open.weibo.com/wiki/Oauth2/authorize)
var oAuthURL: URL{
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
return URL(string: urlString)!
}
/// 加载 AccessToken
/// - Parameters:
/// - code: code
/// - finished: 回调
func loadAccessToken(code: String, finished: @escaping requestCallBack){
let urlString = "https://api.weibo.com/oauth2/access_token"
let params : [String: Any] = ["client_id": appKey, "client_secret": appSecret, "grant_type":"authorization_code", "code": code, "redirect_uri": redirectUrl]
request(method: .POST, URLString: urlString, parameters: params, finished: finished)
}
}
//MARK: - 封装 AFN 网络方法
extension NetworkTools{
/// 网络请求
/// - Parameters:
/// - method: GET / POST
/// - URLString: URLString
/// - parameters: 参数字典
/// - finished: 完成回调
private func request(method: RequestMethod, URLString: String, parameters: [String: Any]?, finished: @escaping requestCallBack){
let methodName = (method == .GET) ? "GET" : "POST"
dataTask(withHTTPMethod: methodName, urlString: URLString, parameters: parameters, headers: nil, uploadProgress: nil, downloadProgress: nil) { _, result in
finished(result,nil)
} failure: { _, error in
print(error)
finished(nil,error)
}?.resume()
}
/// 网络请求
/// - Parameters:
/// - method: GET / POST
/// - URLString: URLString
/// - parameters: 请求参数
/// - headers: 协议头参数
/// - finished: 完成回调
private func request(method: RequestMethod, URLString: String, parameters: [String: Any]?, headers: [String: String]?, finished: @escaping requestCallBack){
//定义成功回调
let success = { (task: URLSessionDataTask, result: Any?) in
finished(result,nil)
}
//定义失败回调
let failure = {(task: URLSessionDataTask?, error: Error) in
finished(nil,error)
}
if(method == .GET){
get(URLString, parameters: parameters, headers: headers, progress: nil, success: success, failure: failure)
}else{
post(URLString, parameters: parameters, headers: headers, progress: nil, success: success, failure: failure)
}
}
}
8. OAuthViewController.swift 调用
import UIKit
import WebKit
///用户登录控制器
class OAuthViewController: UIViewController {
private lazy var webView = WKWebView();
//MARK: - 监听方法
@objc private func close(){
dismiss(animated: true)
}
//自动填充用户名和密码 - web 注入 (以代码的方式向 web 页面添加内容)
@objc private func autoFill(){
let js = "document.getElementById('loginName').value = '153******67';" +
"document.getElementById('loginPassword').value = 'y********2';"
javaScript(js: js)
}
private func javaScript(js: String){
//让 webView 执行 js
webView.evaluateJavaScript(js)
}
override func viewDidAppear(_ animated: Bool) {
//let js = "window.location.href = document.getElementById('jump_login_url_a').getAttribute('href');"
//javaScript(js: js)
}
//MARK: - 设置界面
override func loadView() {
view = webView
//设置代理
webView.uiDelegate = self
webView.navigationDelegate = self
//设置导航栏
title = "登录新浪微博"
//关闭按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
}
override func viewDidLoad() {
super.viewDidLoad()
//在开发中,如果用纯代码开发,视图最好都指定背景颜色,如果 nil
//view.backgroundColor = UIColor.white
//加载页面
let request = NSMutableURLRequest(url: NetworkTools.sharedTools.oAuthURL)
request.setValue("iPad", forHTTPHeaderField: "User-Agent")
self.webView.load(request as URLRequest)
}
}
//MARK: - WKUIDelegate
extension OAuthViewController: WKUIDelegate, WKNavigationDelegate{
/// 收到相应后,决定是否跳转 --> 默认允许
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//目标 : 如果是百度就不加载
//1. 判断访问的主机是否是 www.baidu.com
print("request = \(navigationAction.request)" )
guard let url = navigationAction.request.url , url.host=="www.baidu.com" else {
decisionHandler(.allow)
return
}
//2.从百度地址的 URL 中提取 code = 是否存在
guard let query = url.query , query.hasPrefix("code=") else {
//print("取消授权")
//不允许跳转
decisionHandler(.cancel)
return
}
//3.从 query 字符串中提取 "code=" 后面的授权码
let indexN = query.index(query.startIndex, offsetBy: "code=".count)
let code = query[indexN ..< query.endIndex].description
print("授权码是: " + code)
//4.加载 accessToken
NetworkTools.sharedTools.loadAccessToken(code: code) { result, error in
// 1.判断出错
if error != nil{
print("出错")
return
}
//2.输出结果
print(result ?? "")
}
//不允许跳转
decisionHandler(.cancel)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)