您的位置:首页 > 移动开发 > 微信开发

iOS微信登录功能的实现

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


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

最新的WeChatSDK_1.5支持在未安装微信情况下Auth,检测到设备没有安装微信时,会弹出一个“输入与微信绑定的手机号”的界面:



所以.h文件要声明微信的delegate,并在.m文件将delegate设为self:

[code]@interface WeChatLoginViewController : UIViewController <WXApiDelegate>


.m文件完整代码如下:
[code]#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方法可能会处理一些其它的东西,不能直接像上面一样重写时,就需要做个判断了:
[code] // wechat login delegate
    if ([sourceApplication isEqualToString:@"com.tencent.xin"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }


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

1) WeChatLoginViewController的viewDidload里注册self为观察者:
[code][[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWeChatLoginCode:) name:@"WeChatLoginCode" object:nil];


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


2) AppDelegate里获取code后发送通知:
[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文档。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: