日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

基于Swift语言开发微信、QQ跟微博的SSO授权登录代码分析

發布時間:2023/12/20 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于Swift语言开发微信、QQ跟微博的SSO授权登录代码分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉自:http://www.myexception.cn/swift/1991018.html

前言

Swift 語言,怎么說呢,有一種先接受后排斥,又歡迎的感覺,縱觀國外大牛開源框架或項目演示,Swift幾乎占據了多半,而國內雖然出現很多相關技術介紹和教程,但是在真正項目開發中使用的占據很少部分,原因一是目前熟練它的開發者并不多,二是版本不太穩定,還需要更成熟可靠的版本支持,但總之未來還是很有前景的,深有體會,不管是代碼量還是編譯效率,以及語言特性,現代性都優于Object-C,估計后續會被蘋果作為官方開發語言,值得期待。

走起

鑒于此,筆者將之前用Object-C寫的SSO授權登錄:微信,QQ和微博,重新用Swift語言寫一遍,以便需要的朋友參考,算是SSO授權登錄的姊妹篇;

一、總體架構

1、引入第三方庫

除了必須引入對應的登錄SDK外,額外引入了SDWebImage,SVProgressHUD,看名字大家都明白吧,引入登錄SDK請各自看官方的開發文檔,需要加入什么系統庫文件,需要配置Other Linker Flags 等,請參考各自官方文檔即可;

2、配置連接橋文件

因為創建的工程是基于Swift語言,目前官方SDK和其它三方庫都是用OC寫的,所以為了在swift中調用oc代碼,需要配置連接橋文件Bridging-Header.h,搜索objective-C bridging Header健,然后在值里面輸入XXXLogin/Bridging-Header.h,注意是絕對路徑,里面可以輸入需要調用的頭文件,如

#import "WXApi.h" #import "SVProgressHUD.h" #import "UIImageView+WebCache.h"

3、配置工程

因為是SSO跳轉方式,需要配置URL Schemes,以便程序返回識別宿主程序,配置方法很簡單,參考各自文檔即可,在info里面可以可視化添加,各自的key值采用官方demo所提供;

二、微信

1、注冊

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {// Override point for customization after application launch.//向微信注冊WXApi.registerApp(kWXAPP_ID)return true }

2、授權登錄

override func viewDidLoad() {super.viewDidLoad()NSNotificationCenter.defaultCenter().addObserver(self, selector:"onRecviceWX_CODE_Notification:", name: "WX_CODE", object: nil)let sendBtn:UIButton = UIButton()sendBtn.frame = CGRectMake(30, 100, kIPHONE_WIDTH-60, 40)sendBtn.backgroundColor = UIColor.redColor()sendBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)sendBtn.setTitle("Swift版本之微信授權登錄", forState: UIControlState.Normal)sendBtn.addTarget(self, action: "sendBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)self.view.addSubview(sendBtn)headerImg = UIImageView(frame: CGRectMake(30, 160, 120, 120))headerImg.backgroundColor = UIColor.yellowColor()self.view.addSubview(headerImg)nicknameLbl.frame = CGRectMake(170, 160, kIPHONE_WIDTH-60-140, 40)nicknameLbl.backgroundColor = UIColor.lightGrayColor()nicknameLbl.textColor = UIColor.purpleColor()nicknameLbl.textAlignment = NSTextAlignment.Centerself.view.addSubview(nicknameLbl) }func sendBtnClick(sneder:UIButton){sendWXAuthRequest() }//微信登錄 第一步 func sendWXAuthRequest(){let req : SendAuthReq = SendAuthReq()req.scope = "snsapi_userinfo,snsapi_base"WXApi .sendReq(req) }

3、回調

func onResp(resp: BaseResp!) {/*ErrCode ERR_OK = 0(用戶同意)ERR_AUTH_DENIED = -4(用戶拒絕授權)ERR_USER_CANCEL = -2(用戶取消)code 用戶換取access_token的code,僅在ErrCode為0時有效state 第三方程序發送時用來標識其請求的唯一性的標志,由第三方程序調用sendReq時傳入,由微信終端回傳,state字符串長度不能超過1Klang 微信客戶端當前語言country 微信用戶當前國家信息*/// var aresp resp :SendAuthResp!var aresp = resp as! SendAuthResp// var aresp1 = resp as? SendAuthRespif (aresp.errCode == 0){println(aresp.code)//031076fd11ebfa5d32adf46b37c75aaxvar dic:Dictionary<String,String>=["code":aresp.code];let value = dic["code"]println("code:\(value)")NSNotificationCenter.defaultCenter().postNotificationName("WX_CODE", object: nil, userInfo: dic)} }

4、獲取用戶信息

//微信回調通知,獲取code 第二步 func onRecviceWX_CODE_Notification(notification:NSNotification){SVProgressHUD.showSuccessWithStatus("獲取到code", duration: 1)var userinfoDic : Dictionary = notification.userInfo!let code: String = userinfoDic["code"] as! Stringprint("Recevice Code: \(code)")self.getAccess_token(code) }//獲取token 第三步 func getAccess_token(code :String){//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_codevar requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(kWXAPP_ID)&secret=\(kWXAPP_SECRET)&code=\(code)&grant_type=authorization_code"dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {var requestURL: NSURL = NSURL(string: requestUrl)!var data = NSData(contentsOfURL: requestURL, options: NSDataReadingOptions(), error: nil)dispatch_async(dispatch_get_main_queue(), {var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionaryprintln("Recevice Token: \(jsonResult)")SVProgressHUD.showSuccessWithStatus("獲取到Token和openid", duration: 1)let token: String = jsonResult["access_token"] as! Stringlet openid: String = jsonResult["openid"] as! Stringself.getUserInfo(token, openid: openid)})}) }//獲取用戶信息 第四步 func getUserInfo(token :String,openid:String){// https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENIDvar requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=\(token)&openid=\(openid)"dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {var requestURL: NSURL = NSURL(string: requestUrl)!var data = NSData(contentsOfURL: requestURL, options: NSDataReadingOptions(), error: nil)dispatch_async(dispatch_get_main_queue(), {var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionaryprint("Recevice UserInfo: \(jsonResult)")/*Recevice UserInfo:{city = Chaoyang;country = CN;headimgurl = "http://wx.qlogo.cn/mmopen/FrdAUicrPIibcpGzxuD0kjfssQogj3icL8QTJQYUCLpgzSnvY6rJFGORreicPUiaPCzojwNlsXq4ibbc8e3gGFricWqJU5ia7ibicLVhfT/0";language = "zh_CN";nickname = "\U706b\U9505\U6599";openid = "oyAaTjkR8T6kcKWyA4VPYDa_Wy_w";privilege = ();province = Beijing;sex = 1;unionid = "o1A_Bjg52MglJiEjhLmB8SyYfZIY";}*/SVProgressHUD.showSuccessWithStatus("獲取到用戶信息", duration: 1)let headimgurl: String = jsonResult["headimgurl"] as! Stringlet nickname: String = jsonResult["nickname"] as! Stringself.headerImg.sd_setImageWithURL(NSURL(string: headimgurl))self.nicknameLbl.text = nickname})}) }

5、跳轉

//微信的跳轉回調 func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {return WXApi.handleOpenURL(url, delegate: self) } func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {return WXApi.handleOpenURL(url, delegate: self) }

三、QQ

1、注冊

func sendBtnClick(sneder:UIButton){sendQQAuthRequest() }//第一步 QQ登錄 func sendQQAuthRequest(){tencentOAuth = TencentOAuth(appId: kQQAPP_ID, andDelegate: self)var permissions = [kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO]tencentOAuth.authorize(permissions, inSafari: false) }

2、授權登錄

如上

3、回調

//第二步 登錄成功回調 func tencentDidLogin() {let accessToken = tencentOAuth.accessTokenprintln("accessToken:\(accessToken)") //641B23508B62392C52D6DFADF67FAA9CgetUserInfo() }//失敗 func tencentDidNotLogin(cancelled: Bool) {println("登錄失敗了") }//無網絡 func tencentDidNotNetWork() {println("沒有網絡") }

4、獲取用戶信息

//第三步 獲取用戶信息 func getUserInfo(){SVProgressHUD.showWithStatus("正在獲取用戶信息...")tencentOAuth.getUserInfo() }//第四步 在獲取用戶回調中獲取用戶信息 func getUserInfoResponse(response: APIResponse!) { SVProgressHUD.dismissWithSuccess("獲取用戶信息成功", afterDelay: 1)var dic:Dictionary = response.jsonResponseprintln("dic:\(dic)")// [is_lost: 0, figureurl: http://qzapp.qlogo.cn/qzapp/222222/C5527A2F775D9EA7C20317128FAC202B/30, vip: 0, is_yellow_year_vip: 0, province: 北京, ret: 0, is_yellow_vip: 0, figureurl_qq_1: http://q.qlogo.cn/qqapp/222222/C5527A2F775D9EA7C20317128FAC202B/40, yellow_vip_level: 0, level: 0, figureurl_1: http://qzapp.qlogo.cn/qzapp/222222/C5527A2F775D9EA7C20317128FAC202B/50, city: 海淀, figureurl_2: http://qzapp.qlogo.cn/qzapp/222222/C5527A2F775D9EA7C20317128FAC202B/100, nickname: 竹中雨滴, msg: , gender: 男, figureurl_qq_2: http://q.qlogo.cn/qqapp/222222/C5527A2F775D9EA7C20317128FAC202B/100]refeshUserInfo(dic) }//第五步 刷新用戶界面 func refeshUserInfo(dic : NSDictionary){let headimgurl: String = dic["figureurl_qq_2"] as! Stringlet nickname: String = dic["nickname"] as! String self.headerImg.sd_setImageWithURL(NSURL(string: headimgurl))self.nicknameLbl.text = nickname }

5、跳轉

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {return TencentOAuth.HandleOpenURL(url) }func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {return TencentOAuth.HandleOpenURL(url) }

四、微博

1、注冊

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {// Override point for customization after application launch.WeiboSDK.registerApp(kAppKey)return true }

2、授權登錄

func sendBtnClick(sneder:UIButton){sendSinaAuthRequest() }//第一步 微博登錄 func sendSinaAuthRequest(){var request : WBAuthorizeRequest = WBAuthorizeRequest.request() as! WBAuthorizeRequestrequest.redirectURI = kRedirectURIrequest.scope = "all"request.userInfo = ["SSO_Key":"SSO_Value"]WeiboSDK.sendRequest(request) }

3、回調

func didReceiveWeiboRequest(request: WBBaseRequest!) {}func didReceiveWeiboResponse(response: WBBaseResponse!) {if response.isKindOfClass(WBAuthorizeResponse){if (response.statusCode == WeiboSDKResponseStatusCode.Success) {var authorizeResponse : WBAuthorizeResponse = response as! WBAuthorizeResponsevar userID = authorizeResponse.userIDvar accessToken = authorizeResponse.accessTokenprintln("userID:\(userID)\naccessToken:\(accessToken)")var userInfo = response.userInfo as DictionaryNSNotificationCenter.defaultCenter().postNotificationName("SINA_CODE", object: nil, userInfo: userInfo)}} }

4、獲取用戶信息

//第二步 通過通知得到登錄后獲取的用戶信息 func onRecviceSINA_CODE_Notification(notification:NSNotification) {SVProgressHUD.showSuccessWithStatus("獲取到用戶信息", duration: 1)var userinfoDic : Dictionary = notification.userInfo!println("userInfo:\(userinfoDic)")/*userID:2627289515accessToken:2.002BqnrCyY87OC80500cab28Ofqd3BuserInfo:[uid: 2627289515, remind_in: 647057, scope: invitation_write, refresh_token: 2.002BqnrCyY87OC10f7877765yPietB,app: {logo = "http://ww1.sinaimg.cn/square/65745bf7jw1ea399us692j2028028glf.jpg";name = "SDK\U5fae\U535a\U5e94\U7528demo";}, access_token: 2.002BqnrCyY87OC80500cab28Ofqd3B, expires_in: 647057]*/var userAppInfo: Dictionary<String,String> = userinfoDic["app"] as! DictionaryrefeshUserInfo(userAppInfo) }//第三步 刷新用戶界面 func refeshUserInfo(dic : NSDictionary){let headimgurl: String = dic["logo"] as! Stringlet nickname: String = dic["name"] as! Stringself.headerImg.sd_setImageWithURL(NSURL(string: headimgurl))self.nicknameLbl.text = nickname }

5、跳轉

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {return WeiboSDK.handleOpenURL(url, delegate: self) }func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {return WeiboSDK.handleOpenURL(url, delegate: self) }

五、對比分析

1、demo情況

微博demo代碼工整度完爆微信,QQ,看著很舒服,心情也不錯;另外微博放在了github上面,適合pod管理,注釋也極好,微信文檔寫的挺不錯,QQ寫的簡直喪心病狂,需要極度耐心才能看明白,表示很無語,另外本三種方式授權登錄的源代碼有償提供,如需可以郵件mmw05@163.com即可;

2、嵌入時間

微信算是很容易嵌入SDK,QQ也還可以,微博需要注意boundID有限制,微信的邏輯算是比較冗余繁瑣,從授權到獲取到用戶信息需要很多接口,而QQ和微博可以直接從授權登陸回調中獲取到,是比較便捷的,從上面代碼可以看出來;

后記

從objective-C到Swift,蘋果力求簡約,但又不簡單,現代化的語言,必然在性能各方面優于傳統,只是需要時間和更多的考驗,作為開發者,多一個選擇,豈不更好!
附圖:

總結

以上是生活随笔為你收集整理的基于Swift语言开发微信、QQ跟微博的SSO授权登录代码分析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。