1. 程式人生 > >iOS微信登入功能的實現

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