iOS微信登录功能的实现

iOS应用接入微信的主要步骤,在微信开放平台的文档已经讲得很清楚了,按照微信官方的文档(iOS接入指南移动应用微信登录开发指南)一步一步去做就行了,我就不赘述了,这里主要讲一下代码中几个需要注意的地方。

1. 使用微信登录功能的ViewController

最新的WeChatSDK_1.5支持在未安装微信情况下Auth,检测到设备没有安装微信时,会弹出一个“输入与微信绑定的手机号”的界面:
这里写图片描述
所以.h文件要声明微信的delegate,并在.m文件将delegate设为self:

@interface WeChatLoginViewController : UIViewController <WXApiDelegate>

.m文件完整代码如下:

#pragma mark - WeChat login
- (IBAction)weChatLogin:(UIButton *)sender {
    [self sendAuthRequest];
}

- (void)sendAuthRequest {
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"0123" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendAuthReq:req viewController:self delegate:self];
}

2. AppDelegate

微信登录需要在你的应用和微信之间跳转,所以必须借助AppDelegate来实现。AppDelegate文件需要做的事情有:
1) .h文件声明delegate
这里写图片描述
2) 在didFinishLaunchingWithOptions 函数中向微信注册id:
这里写图片描述
3) 重写AppDelegate的handleOpenURL和openURL方法:
这里写图片描述
有时候handleOpenURL和openURL方法可能会处理一些其它的东西,不能直接像上面一样重写时,就需要做个判断了:

 // wechat login delegate
    if ([sourceApplication isEqualToString:@"com.tencent.xin"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }

3. 获取code后将code传回WeChatLoginViewController,可以用notification的方式来实现

1) WeChatLoginViewController的viewDidload里注册self为观察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWeChatLoginCode:) name:@"WeChatLoginCode" object:nil];

收到通知后执行的方法:

- (void)getWeChatLoginCode:(NSNotification *)notification {
    NSString *weChatCode = [[notification userInfo] objectForKey:@"code"];
    /*
    使用获取的code换取access_token,并执行登录的操作
    */    
}

2) AppDelegate里获取code后发送通知:

- (void)onResp:(BaseReq *)resp {
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if (aresp.errCode== 0) {
        NSString *code = aresp.code;
        NSDictionary *dictionary = @{@"code":code};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WeChatLoginCode" object:self userInfo:dictionary];
    }
}

微信登录的整体流程:

1) app启动时向微信终端注册你的app id;
2) 按下(IBAction)weChatLogin按钮,你的app向微信发送请求。AppDelegate使用handleOpenURL和openURL方法跳转到微信;
3) 获取到code后AppDelegate发送通知并传递code;
4) WeChatLoginViewController收到通知及传递的code后,换取access_token并执行登录等相关操作。

以上就是微信登录的大致流程了,还有很多细节(如获取微信个人信息、刷新access_token等)可以查看微信的Api文档。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章