微信登陸

AppDelegate

#import "AppDelegate.h"

#import "WeChatSDK1.8.3_NoPay/WXApi.h"

#import "MBProgressHUD/MBProgressHUD.h"

@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate

#pragma mark --------- 顯示提示框 ---------

// 顯示提示框

-(void)showMBAlertWithMessage:(NSString*)msg {

? ? MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:self.window];

? ? hud.mode = MBProgressHUDModeText; // 設(shè)置文本樣式

? ? hud.labelText= msg;? ? // 設(shè)置顯示的提示文本

? ? hud.removeFromSuperViewOnHide = YES;

? ? [self.windowaddSubview:hud];

? ? [hudshow:YES];

? ? [hudhide:YES afterDelay:3.0];

}

#pragma mark --------- 獲取微信信息 ----------

// 通過code獲取access_token

-(void)getAccessTokenWithCode:(NSString*)code {

? ? // (1)網(wǎng)址字符串拼接

? ? NSString *appID = @"wx537cf8aac45b25df";


? ? NSString *appSecret = @"879024ead533e25662a7fa7ca1dcc940";


? ? NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",appID,appSecret,code];


? ? NSURL *url = [NSURL URLWithString:urlStr];


? ? [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

? ? ? ? if(error !=nil) {

? ? ? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{

? ? ? ? ? ? ? ? [self showMBAlertWithMessage:@"登錄失敗"];

? ? ? ? ? ? });

? ? ? ? ? ? return;

? ? ? ? }


? ? ? ? id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

? ? ? ? NSLog(@"json====%@",jsonData);

? ? ? ? // 獲取access_token 和 openID

? ? ? ? NSString*access_token = jsonData[@"access_token"];

? ? ? ? NSString*openid = jsonData[@"openid"];

? ? ? ? // 通過token和id得到微信用戶信息

? ? ? ? [selfgetWXUserInfoWithToken:access_tokenopenID:openid];

? ? }]resume];

}

// 通過token和openID獲取微信用戶信息

-(void)getWXUserInfoWithToken:(NSString*)accessToken openID:(NSString*)openID {


? ? // (1)

? ? NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openID];

? ? // (2)

? ? NSURL *url = [NSURL URLWithString:urlStr];

? ? // (3)

? ? [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

? ? ? ? if(error !=nil) {

? ? ? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{

? ? ? ? ? ? ? ? [self showMBAlertWithMessage:@"微信登錄失敗"];

? ? ? ? ? ? });

? ? ? ? ? ? return;

? ? ? ? }

? ? ? ? id userInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

? ? ? ? NSLog(@"userJson======%@",userInfo);


? ? ? ? // 持久化數(shù)據(jù)

? ? ? ? [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"loginUser"];

? ? ? ? [[NSUserDefaults standardUserDefaults] synchronize];


? ? ? ? // 切換窗口的根視圖控制器

? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{

? ? ? ? ? ? self.window.rootViewController=self.mainVC;

? ? ? ? });

? ? }]resume];

}

#pragma mark -------- WXApiDelegate --------

// 從微信app返回當(dāng)前app調(diào)用的回調(diào)

-(void)onResp:(BaseResp*)resp {

? ? // 如果是授權(quán)登錄的回調(diào)

? ? if([respisKindOfClass:[SendAuthRespclass]]) {


? ? ? ? // 獲取微信返回的code值

? ? ? ? SendAuthResp*authResp = (SendAuthResp*)resp;

? ? ? ? // 授權(quán)成功

? ? ? ? if(authResp.errCode==0) {

? ? ? ? ? ? // 得到返回的code值

? ? ? ? ? ? NSString*code = authResp.code;

? ? ? ? ? ? NSLog(@"code===%@",code);

? ? ? ? ? ? // 獲取access_token

? ? ? ? ? ? [self getAccessTokenWithCode:code];

? ? ? ? }

? ? ? ? // 拒絕授權(quán)

? ? ? ? elseif(authResp.errCode== -4) {

? ? ? ? ? ? [self showMBAlertWithMessage:@"拒絕授權(quán)"];

? ? ? ? }

? ? ? ? // 取消授權(quán)

? ? ? ? elseif(authResp.errCode== -2){

? ? ? ? ? ? [self showMBAlertWithMessage:@"取消授權(quán)"];

? ? ? ? }



? ? }

? ? // 如果是分享的回調(diào)

? ? elseif([respisKindOfClass:[SendMessageToWXRespclass]]) {


? ? }


}

#pragma mark ------- 控制器實例化 --------

-(MainViewController *)mainVC {

? ? if(!_mainVC) {

? ? ? ? _mainVC = [[MainViewController alloc] init];

? ? }

? ? return _mainVC;

}

-(ViewController *)loginVC {

? ? if(!_loginVC) {

? ? ? ? _loginVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateInitialViewController];

? ? }

? ? return _loginVC;

}

#pragma mark --------- UIApplicationDelegate -------

-(BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {

? ? return [WXApi handleOpenURL:url delegate:self];

}

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

? ? // Override point for customization after application launch.

? ? // 向微信注冊應(yīng)用

? ? [WXApi registerApp:@"wx537cf8aac45b25df"];





? ? // 有持久化數(shù)據(jù),表示登錄過,將mainVC設(shè)置為窗口的根視圖控制器

? ? if ([[NSUserDefaults standardUserDefaults] objectForKey:@"loginUser"] != nil) {

? ? ? ? self.window.rootViewController = self.mainVC;

? ? }

? ? // 沒有持久化數(shù)據(jù),表示未登錄,將loginVC設(shè)置為窗口的根視圖控制器

? ? else{

? ? ? ? self.window.rootViewController = self.loginVC;

? ? }

? ? return YES;

}





ViewController



#import "AppDelegate.h"

#import "WeChatSDK1.8.3_NoPay/WXApi.h"

- (IBAction)weChatLogin:(id)sender;


- (IBAction)weChatLogin:(id)sender {

? ? //構(gòu)造SendAuthReq結(jié)構(gòu)體

? ? SendAuthReq* req = [[SendAuthReq alloc]init];

? ? req.scope = @"snsapi_userinfo";

? ? req.state=@"123";

? ? //第三方向微信終端發(fā)送一個SendAuthReq消息結(jié)構(gòu)

? ? [WXApisendReq:req];

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容