// // GiGaUserLoginVC.m // GIGA // // Created by lianxiang on 2018/8/20. // Copyright © 2018年 com.giga.ios. All rights reserved. // #import "GiGaUserLoginVC.h" #import "UINavigationBar+Custom.h" #import "PassWordResetVC.h" #import "GiGaRegistViewController.h" #import "GiGaUserDefault.h" #import "WXApi.h" #import "GiGaNetManager.h" #import "WeiIXinApiManager.h" #import "GiGaBaseAPiRequest.h" #import "GiGaUser.h" #import "GiGaServerConfig.h" #import "GIGAMBHUDHelper.h" #import "GiGaHelper.h" #import "GiGaUserManager.h" #import "NSTimer+Convenience.h" @interface GiGaUserLoginVC () @property (weak, nonatomic) IBOutlet UIImageView *userImagView; @property (weak, nonatomic) IBOutlet UITextField *acountTextField; //0.9+ 改成code @property (weak, nonatomic) IBOutlet UITextField *passwordTextField; @property (weak, nonatomic) IBOutlet UIButton *loginBtn; @property (weak, nonatomic) IBOutlet UIButton *weiXinLoginBtn; @property (weak, nonatomic) IBOutlet UIButton *registBtn; @property (weak, nonatomic) IBOutlet UIButton *secretBtn; @property(nonatomic,strong) NSTimer*timer; @property(nonatomic) NSInteger time; @end @implementation GiGaUserLoginVC - (void)viewDidLoad { [super viewDidLoad]; _time = 60; if (@available(iOS 11.0, *)) { self.backScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; } else { self.automaticallyAdjustsScrollViewInsets = NO; // Fallback on earlier versions } // Do any additional setup after loading the view from its nib. [self setUpX]; [self textFieldUI]; [self.view bringSubviewToFront:self.weiXinLoginBtn]; [self.registBtn addTarget:self action:@selector(registBtnAction) forControlEvents:UIControlEventTouchUpInside]; [self.loginBtn addTarget:self action:@selector(loginBtnAction:) forControlEvents:UIControlEventTouchUpInside]; [self.weiXinLoginBtn addTarget:self action:@selector(weiXinLoginAction) forControlEvents:UIControlEventTouchUpInside]; [self.secretBtn addTarget:self action:@selector(secretBtnAction:) forControlEvents:UIControlEventTouchUpInside]; NC_ADD_TARGET_NAME_OBJECT(self, @selector(WeiXinLongIn:), kWeiXinAuthrization_Success, nil) NC_ADD_TARGET_NAME_OBJECT(self, @selector(userRegistSuccsessNoti:), kUserRegistSucccess, nil) if (![WXApi isWXAppInstalled]) { self.weiXinLoginBtn.hidden = YES; } } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [self.navigationController.navigationBar setClearNav]; } -(void)dealloc{ NC_REMOVE_NAME(self, kWeiXinAuthrization_Success,nil); } -(void)setUpX{ UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom]; rightBtn.frame = CGRectMake(0, 0, 40, 40); [rightBtn setImage:[UIImage imageNamed:@"btn_back"] forState:UIControlStateNormal]; [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn]; } -(void)textFieldUI{ UIView *acountView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; UIImageView *acountViewIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15,9, 12, 22)]; acountViewIcon.image = [UIImage imageNamed:@"ic_number"]; [acountView addSubview:acountViewIcon]; self.acountTextField.leftView = acountView; self.acountTextField.leftViewMode = UITextFieldViewModeAlways; // NSAttributedString *passholderText = [[NSAttributedString alloc] initWithString:@"密码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}]; // self.passwordTextField.attributedPlaceholder = passholderText; UIView *passView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; UIImageView *passViewIcon = [[UIImageView alloc] initWithFrame:CGRectMake(12,13.5, 18, 13)]; passViewIcon.image = [UIImage imageNamed:@"ic_note"]; [passView addSubview:passViewIcon]; self.passwordTextField.leftView = passView; self.passwordTextField.leftViewMode = UITextFieldViewModeAlways; self.loginBtn.layer.masksToBounds = YES; self.loginBtn.layer.cornerRadius = self.loginBtn.frame.size.height / 2; NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] init]; NSTextAttachment *attch = [[NSTextAttachment alloc] init]; attch.image = [UIImage imageNamed:@"ic_wechat"]; attch.bounds = CGRectMake(0,-4, 12.9, 12.5); NSAttributedString *imastr=[NSAttributedString attributedStringWithAttachment:attch]; [attri appendAttributedString:imastr]; NSAttributedString *titleStr = [[NSAttributedString alloc] initWithString:@" 微信账号登录" attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Semibold" size:10],NSForegroundColorAttributeName:[UIColor colorWithRed:187/255.0 green:187/255.0 blue:187/255.0 alpha:1/1.0]}]; [attri appendAttributedString:titleStr]; [self.weiXinLoginBtn setAttributedTitle:attri forState:UIControlStateNormal]; } -(void)rightBtnAction{ [self dismissViewControllerAnimated:YES completion:nil]; } -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = NO; } } -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (IBAction)forgetPassBtn:(id)sender { PassWordResetVC *passVC= [[PassWordResetVC alloc] init]; [self.navigationController pushViewController:passVC animated:YES]; [self.navigationController.navigationBar setBackgroundImage]; } #pragma mark - 去注册 -(void)registBtnAction{ GiGaRegistViewController *registVC = [[GiGaRegistViewController alloc] init]; [self.navigationController pushViewController:registVC animated:YES]; } #pragma mark 手机号登录 验证码登录 -(void)loginBtnAction:(UIButton *)btn{ if (self.acountTextField.text.length == 0) { GIGA_ShowToast(@"请输入手机号"); return; } if (![GiGaHelper isPhoneNumber:self.acountTextField.text]) { GIGA_ShowToast(@"请输入正确手机号"); return; } if (self.passwordTextField.text.length == 0) { GIGA_ShowToast(@"密码不能为空"); return; } if (self.passwordTextField.text.length == 0) { GIGA_ShowToast(@"请输入验证码"); return; } [self loginWithAction:btn]; } -(void)loginWithAction:(UIButton *)btn{ // NSDictionary *weixinInfoDic = [GiGaUserDefault getWeiXinAccessToenDic]; NSString *wechatCode = [GiGaUserDefault getWeiXinCode]; if (wechatCode==nil) { wechatCode = @""; } NSDictionary *params = nil; params = @{ @"mobile":self.acountTextField.text, @"code":self.passwordTextField.text, @"wechatCode":wechatCode, }; //[GIGAMBHUDHelper messageAddto:self.view title:@"登录中..."]; [self.view makeToastActivity:CSToastPositionCenter]; //NSString *baseapi = [GiGaServerConfig getMainUrl]; //NSString *url = [NSString stringWithFormat:@"%@%@",baseapi,kApiUserloginWithSMSCode]; // [GiGaNetManager userbodyRequest:url params:params completionHandler:^(NSURLResponse *response, NSDictionary *resDic, NSError * _Nullable error) { // GILog(@"%@",resDic); // [self.view hideToastActivity]; // GiGaAPIResult *result = [[GiGaAPIResult alloc] initWithDictionary:resDic]; // GILog(@"**登陆***\n code:%ld\n message:%@\n *******\n",result.code,result.message); // if (result.success) { // [self userloginSussecess:resDic]; // }else{ // GIGA_ShowToast(result.message); // } // }]; //[GIGAMBHUDHelper messageAddto:self.view title:@"登录中..."]; [self.view makeToastActivity:CSToastPositionCenter]; GiGaBaseAPiRequest *api = [GiGaBaseAPiRequest initWithRequestPath:kApiUserloginWithSMSCode method:RequestPostMethod parms:params]; [api requstDataWithResult:^(GiGaAPIResult *result) { [self.view hideToastActivity]; GILog(@"**登陆***\n code:%ld\n message:%@\n *******\n",result.code,result.message); if (result.success) { [self userloginSussecess:result.dic]; }else{ GIGA_ShowToast(result.message); } }]; } -(void)saveUserData{ //埋点 [MobClick endEvent:MobClick_UserLogin]; [GiGaUserDefault saveUserId:@"123"]; } #pragma mark - 微信登录 // 授权 -(void)weiXinLoginAction{ if ([WXApi isWXAppInstalled]) { SendAuthReq * req = [[SendAuthReq alloc] init] ; req.scope = @"snsapi_userinfo"; req.state = @"wx_oauth2_authorization_state"; [WXApi sendReq:req]; } } //授权成功获取access_token(改服务器获取) -(void)WeiXinLongIn:(NSNotification *)notification{ //保存code 首次授权微信登陆需要先绑定手机号(必须注册手机账号) [GiGaUserDefault saveWeiXinCode:notification.object[@"code"]]; [self.view makeToastActivity:CSToastPositionCenter]; NSDictionary *param = @{ @"code":notification.object[@"code"] }; [self gigaUploadweixinInfo:param]; // NSDictionary *param = @{ // @"appid":WXin_APPID, // @"secret":WXin_APPSecret, // @"code":notification.object[@"code"], // @"grant_type":@"authorization_code" // }; // // [WeiIXinApiManager weixinAccessTokeRequstUrl:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:param success:^(id response) { // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil]; // GILog(@"access_token back -->%@",dict); // [GiGaUserDefault saveWeiXinaccesstokenInfoWithDic:dict]; // [self requstWeiXinUserinfo]; // // } failure:^(NSError *err) { // [self.view makeToast:err.localizedDescription]; // GILog(@"access_token err-->%@",err.localizedDescription); // }]; } //获取微信用户信息 (改由服务器请求获取) -(void)requstWeiXinUserinfo{ NSDictionary *tokenDic = [GiGaUserDefault getWeiXinAccessToenDic]; NSDictionary *param = @{ @"openid":tokenDic[@"openid"], @"access_token":tokenDic[@"access_token"], }; [WeiIXinApiManager getWeiXinUserInfoUrl:@"https://api.weixin.qq.com/sns/userinfo" parameters:param success:^(id response) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil]; GILog(@"weixinUser info back -->%@",dict); // [self gigaUploadweixinInfo:dict]; } failure:^(NSError *err) { [self.view makeToast:err.localizedDescription]; GILog(@"weixin_userinfoApi err-->%@",err.localizedDescription); }]; } // 微信登陆 -(void)gigaUploadweixinInfo:(NSDictionary *)weiXinUserinfo{ [self.view makeToastActivity:CSToastPositionCenter]; NSString *url = [NSString stringWithFormat:@"%@%@",[GiGaServerConfig getMainUrl],kApiWeiChatLogin]; [GiGaNetManager requestMethod:RequestPostMethod Url:url params:weiXinUserinfo responseBlock:^(NSDictionary *responseDict, NSDictionary *responseHeaderFields, NSError *error) { [self.view hideToastActivity]; if (!error) { if ([responseDict[@"code"] integerValue] == 0) { [self userloginSussecess:responseDict]; }else{ [self.view makeToast:responseDict[@"msg"] duration:2.0 position:CSToastPositionCenter]; } }else{ [self.view makeToast:@"用户信息提交异常"]; GILog(@"上传微信用户信息error:\n%@",error.localizedDescription); } }]; } //请求用户数据 -(void)userloginSussecess:(NSDictionary *)resDic{ //token 登陆标志 [GiGaUserDefault saveToken:resDic[@"token"]]; weakify(self); [[GiGaUserManager shareUser] synsisUserInfo:^(GiGaUser *user) { GILog(@"user.userId:%@",user.userId); //埋点 [MobClick endEvent:MobClick_UserLogin]; GIGA_WIndowTost(@"登录成功!"); NC_POST_NAME_OBJECT(kUserLoginSuccessNoti, nil); [weakSelf dismissViewControllerAnimated:YES completion:nil]; } userErrorMsgBlock:^(NSDictionary *errorCodemsg) { if (errorCodemsg) { NSString *msg = errorCodemsg[@"msg"]; if (msg) { GIGA_ShowToast(msg); } } }]; } //接收注册成功通知 -(void)userRegistSuccsessNoti:(NSNotification *)noti{ self.acountTextField.text =(NSString *)noti.object; } //短信验证码按钮 -(void)secretBtnAction:(UIButton *)btn{ if (![GiGaHelper isPhoneNumber:self.acountTextField.text]) { GIGA_ShowToast(@"请输入正确手机号"); return; } [MBProgressHUD showHUDAddedTo:self.view animated:YES]; NSString *phoneNumber = self.acountTextField.text; NSDictionary *param = @{ @"mobile":phoneNumber }; GiGaBaseAPiRequest *api = [GiGaBaseAPiRequest initWithRequestPath:kApiIUserLoginSendCode method:RequestPostMethod parms:param]; [api requstDataWithResult:^(GiGaAPIResult *result) { [MBProgressHUD hideHUDForView:self.view animated:YES]; GILog(@"短信获取%@",result.message); if (result.success) { [self startTimer:btn]; }else{ GIGA_ShowToast(result.message); } }]; } //短信登录 验证码倒计时 -(void)startTimer:(UIButton *)btn{ btn.userInteractionEnabled = NO; if (_time>0) { _timer = [NSTimer scheduledTimerWithTimeInterval:1 count:60 callback:^{ NSString *timeStr=[NSString stringWithFormat:@"%lds",(long)self->_time]; [btn setTitle:timeStr forState:UIControlStateNormal]; self->_time--; if (self->_time==0) { [self.secretBtn setTitle:@"发送短信" forState:UIControlStateNormal]; self->_time =60; btn.userInteractionEnabled = YES; } }]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } } @end