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

前言

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()// Do any additional setup after loading the view, typically from a nib.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!) {/*ErrCodeERR_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! Stringprintln("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! NSDictionaryprintln("Recevice UserInfo: \(jsonResult)")/*Recevice UserInfo:{city = Chaoyang;country = CN;headimgurl = "";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 <span style="white-space:pre"></span>{return WXApi.handleOpenURL(url, delegate: self)}三,QQ1,注册 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,授权登录只有这样才不会被“不可能”束缚,才能不断超越自我。

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

相关文章:

你感兴趣的文章:

标签云: