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文檔。

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