微信登陆

AppDelegate

#import "AppDelegate.h"

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

#import "MBProgressHUD/MBProgressHUD.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

#pragma mark --------- 显示提示框 ---------

// 显示提示框

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

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

    hud.mode = MBProgressHUDModeText; // 设置文本样式

    hud.labelText= msg;    // 设置显示的提示文本

    hud.removeFromSuperViewOnHide = YES;

    [self.windowaddSubview:hud];

    [hudshow:YES];

    [hudhide:YES afterDelay:3.0];

}

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

// 通过code获取access_token

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

    // (1)网址字符串拼接

    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);


        // 持久化数据

        [[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返回当前app调用的回调

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

    // 如果是授权登录的回调

    if([respisKindOfClass:[SendAuthRespclass]]) {


        // 获取微信返回的code值

        SendAuthResp*authResp = (SendAuthResp*)resp;

        // 授权成功

        if(authResp.errCode==0) {

            // 得到返回的code值

            NSString*code = authResp.code;

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

            // 获取access_token

            [self getAccessTokenWithCode:code];

        }

        // 拒绝授权

        elseif(authResp.errCode== -4) {

            [self showMBAlertWithMessage:@"拒绝授权"];

        }

        // 取消授权

        elseif(authResp.errCode== -2){

            [self showMBAlertWithMessage:@"取消授权"];

        }



    }

    // 如果是分享的回调

    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.

    // 向微信注册应用

    [WXApi registerApp:@"wx537cf8aac45b25df"];





    // 有持久化数据,表示登录过,将mainVC设置为窗口的根视图控制器

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

        self.window.rootViewController = self.mainVC;

    }

    // 没有持久化数据,表示未登录,将loginVC设置为窗口的根视图控制器

    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 {

    //构造SendAuthReq结构体

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

    req.scope = @"snsapi_userinfo";

    req.state=@"123";

    //第三方向微信终端发送一个SendAuthReq消息结构

    [WXApisendReq:req];

}

你可能感兴趣的:(微信登陆)