123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- //
- // LoginVC.m
- // smartRhino
- //
- // Created by armin on 2019/11/2.
- // Copyright © 2019 tederen. All rights reserved.
- //
- #import "LoginVC.h"
- #import "TabBarController.h"
- #import "WXApi.h"
- #import "EditPhoneOrEmailVC.h"
- @interface LoginVC ()<UITextFieldDelegate>
- //可滚动区域H
- @property (strong,nonatomic) IBOutlet NSLayoutConstraint *scrollH;
-
- @property (strong,nonatomic) IBOutlet UITextField *phoneTextField;
- @property (strong,nonatomic) IBOutlet UIButton *sendYZMBtn;
- @property (strong,nonatomic) IBOutlet UITextField *yzmTextField;
- @property (strong,nonatomic) IBOutlet UIButton *loginBtn;
- @property (strong,nonatomic) IBOutlet UIButton *wechatBtn;
- @end
- @implementation LoginVC
- +(LoginVC *)initLoginVC{
- LoginVC *controller = [StoryboardManager.shared.login instantiateViewControllerWithIdentifier:@"LoginVC"];
- return controller;
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
-
- self.fd_prefersNavigationBarHidden = YES;
-
- self.phoneTextField.text = @"";
- self.phoneTextField.delegate = self;
- self.phoneTextField.placeholder = @"请输入手机号";
- self.phoneTextField.textColor = RGB(51, 51, 51);
- [self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
- UILabel *placeholderLabel = object_getIvar(self.phoneTextField, ivar);
- placeholderLabel.textColor = RGB(153, 153, 153);
-
- [self.sendYZMBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
- self.yzmTextField.text = @"";
- self.yzmTextField.delegate = self;
- self.yzmTextField.placeholder = @"请输入验证码";
- self.yzmTextField.textColor = RGB(51, 51, 51);
- [self.yzmTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- Ivar ivart = class_getInstanceVariable([UITextField class], "_placeholderLabel");
- UILabel *placeholderLabelt = object_getIvar(self.yzmTextField, ivart);
- placeholderLabelt.textColor = RGB(153, 153, 153);
-
- self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
- self.yzmTextField.keyboardType = UIKeyboardTypeNumberPad;
-
- self.loginBtn.layer.masksToBounds = YES;
- self.loginBtn.layer.cornerRadius = 8.0;
- WS(weakSelf);
- [self.loginBtn setAction:^{
- [weakSelf gotoLogin:@""];
- // [weakSelf changeToHome];
- }];
- [self.wechatBtn setAction:^{
- [weakSelf sendWXAuthReq];
- }];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiChatOK:) name:WeiChatSuccess object:NULL];
- }
- #pragma mark - 微信登录成功回调信息
- - (void)sendWXAuthReq{//复制即可
-
- if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
-
- SendAuthReq *req = [[SendAuthReq alloc] init];
- req.state = @"wx_oauth_authorization_state";//用于保持请求和回调的状态,授权请求或原样带回
- req.scope = @"snsapi_userinfo";//授权作用域:获取用户个人信息
- //唤起微信
- [WXApi sendReq:req];
- }else{
- SHOWERROR(@"未安装微信应用或版本过低");
- }
- }
- -(void)weiChatOK:(NSNotification *)noti
- {
- WS(weakSelf);
- NSLog(@"^^^^^^^^%@",noti.userInfo);
- NSDictionary * dic = noti.userInfo;
- NSString * url = [NSString stringWithFormat:@"%@%@",Host(API_App_User_Opend_Id),dic[@"openid"]];
- [[HttpManager sharedHttpManager] GETUrl:url parameters:@{} responseStyle:DATA success:^(id _Nonnull responseObject) {
- NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
- BOOL isOpenId = [str boolValue];
- if (isOpenId) {
- [weakSelf gotoLogin:dic[@"openid"]];
- }else{
- EditPhoneOrEmailVC *vc = [EditPhoneOrEmailVC initEditPhoneOrEmailVC];
- vc.pageType = BindingOrChangePhoneOrEmailPageType5;
- vc.openId = dic[@"openid"];
- [self.navigationController pushViewController:vc animated:NO];
- }
- } failure:^(NSError * _Nonnull error) {
-
- }];
- }
- - (void)gotoLogin:(NSString *)openId{
- if (openId.length == 0) {
- if (self.phoneTextField.text.length != 11) {
- SHOWERROR(@"请输入正确的手机号码")
- return;
- }
- if (self.yzmTextField.text.length != 6) {
- SHOWERROR(@"请输入正确的验证码")
- return;
- }
- }
- SHOWLOADING
- WEAKSELF
- NSLog(@"⚠️ 手机号码 %@ 登录验证码%@",self.phoneTextField.text,self.yzmTextField.text);
- [[HttpManager sharedHttpManager] POSTUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,LoginPost] parameters:@{@"phone":self.phoneTextField.text,@"code":self.yzmTextField.text,@"OpenId":openId} responseStyle:JOSN success:^(id _Nonnull responseObject) {
- NSLog(@"响应结果 %@",responseObject);
- NSDictionary *dic = responseObject;
- USERDEFAULTSSET(dic[@"Token"][@"Expires"],@"tokenExpires");
- NSString *token = [NSString stringWithFormat:@"%@ %@",dic[@"Token"][@"Type"],dic[@"Token"][@"Token"]];
- USERDEFAULTSSET(token,@"LOGINTOKEN");
- NSLog(@"登录成功之后的token%@\n%@",kToken,token);
- USERDEFAULTSSET(dic[@"UserId"],@"userId");
- REMOVESHOW
- [weakSelf getUserInfoDetail];
- } failure:^(NSError * _Nonnull error) {
- REMOVESHOW
- SHOWERROR([ZYCTool handerResultData:error])
- }];
- }
- - (void)getUserInfoDetail{
- SHOWLOADING
- WEAKSELF
- NSLog(@"%@",kUserId);
- [[HttpManager sharedHttpManager].manager.requestSerializer setValue:[UserManager token] forHTTPHeaderField:@"Authorization"];
- [[HttpManager sharedHttpManager] GETUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,UserDetailGet] parameters:@{} success:^(id _Nonnull responseObject) {
- NSLog(@"%@",responseObject);
- AppUserModel * model = [[AppUserModel alloc] initWithDictionary:responseObject error:nil];
- [model saveUserInfor];
- REMOVESHOW
- NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
- USERDEFAULTSSET(data,@"USERINFO");
- //在这里登陆环信
- [[EMClient sharedClient] loginWithUsername:@"13699447785" password:@"123456" completion:^(NSString *aUsername, EMError *aError) {
- EMError *error = aError;
- dispatch_async(dispatch_get_main_queue(), ^{
- if (!error) {
- //设置是否自动登录
- [[EMClient sharedClient].options setIsAutoLogin:YES];
- [weakSelf changeToHome];
- } else {
- [weakSelf changeToLogin];
- NSLog(@"emclient login error:%u",error.code);
- switch (error.code)
- {
- case EMErrorUserNotFound:
- SHOWERROR(@"用户不存在");
- break;
- case EMErrorNetworkUnavailable:
- break;
- case EMErrorServerNotReachable:
- break;
- case EMErrorUserAuthenticationFailed:
- break;
- case EMErrorServerTimeout:
- break;
- case EMErrorServerServingForbidden:
- break;
- case EMErrorInvalidUsername:
- SHOWERROR(@"用户名无效");
- break;
- case EMErrorUserLoginTooManyDevices:
- break;
- case EMErrorUserNotLogin:
- SHOWERROR(@"用户未登陆");
- break;
- default:
- break;
- }
- }
- });
- }];
- } failure:^(NSError * _Nonnull error) {
- REMOVESHOW
- SHOWERROR([ZYCTool handerResultData:error])
- }];
- }
- -(void)changeToLogin{
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"LOGINTOKEN"];
- [[NSUserDefaults standardUserDefaults] synchronize];
- [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
- [[HttpManager sharedHttpManager].manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
- }];
- }
- -(void)changeToHome{
- UIWindow *window = [UtilsTools getWindow];
- window.rootViewController = [TabBarController sharedTabBarController];
- [[TabBarController sharedTabBarController] setSelectedIndex:0];
- [window makeKeyAndVisible];
- }
- - (IBAction)verifyCodeAction:(UIButton *)sender {
- [self.view endEditing:YES];
-
- // [sender setEnabled:NO];
-
-
- if (self.phoneTextField.text.length != 11) {
- SHOWERROR(@"请输入正确的手机号码")
- return;
- }
- NSLog(@"⚠️ 登陆获取验证码 %@",self.phoneTextField.text);
- SHOWLOADING
- [[HttpManager sharedHttpManager] GETUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,LoginSendCodeGet] parameters:@{@"phone":self.phoneTextField.text} responseStyle:DATA success:^(id _Nonnull responseObject) {
- REMOVESHOW
- [self startTime];
- } failure:^(NSError * _Nonnull error) {
- REMOVESHOW
- SHOWERROR([ZYCTool handerResultData:error])
- }];
- // [[HttpManager sharedHttpManager] GET:[NSString stringWithFormat:@"%@%@",BaseUrl,LoginSendCodeGet] parameters:@{@"phone":self.phoneTextField.text} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
- //
- // REMOVESHOW
- // [self startTime];
- // } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
- // REMOVESHOW
- //
- // SHOWERROR([ZYCTool handerResultData:error])
- // }];
-
-
-
- }
- -(void)startTime{
- __block int timeout=60; //倒计时时间
- dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
- dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
- dispatch_source_set_event_handler(_timer, ^{
- if(timeout<=0){ //倒计时结束,关闭
- dispatch_source_cancel(_timer);
- WS(weakSelf);
- dispatch_async(dispatch_get_main_queue(), ^{
- //设置界面的按钮显示 根据自己需求设置 特别注明:UI的改变一定要在主线程中进行
- //倒计时完成,恢复到原来的效果
- weakSelf.sendYZMBtn.enabled = YES;
- NSString *text = @"获取验证码";
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateNormal];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateHighlighted];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateSelected];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateDisabled];
- [weakSelf.sendYZMBtn setTitleColor:RGB(37, 138, 220) forState:UIControlStateNormal];
- [weakSelf.sendYZMBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
- [weakSelf.sendYZMBtn setEnabled:YES];
- });
- }else{
- int seconds = timeout % 60;
- if(seconds == 0&&timeout==60){
- seconds = 60;
- }
- // NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
- WS(weakSelf);
- dispatch_async(dispatch_get_main_queue(), ^{
- //设置界面的按钮显示 根据自己需求设置
- // NSLog(@"____%@",strTime);
- weakSelf.sendYZMBtn.enabled = NO;
- NSString *text = [NSString stringWithFormat:@"重新获取(%lus)",(unsigned long)seconds];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateNormal];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateHighlighted];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateSelected];
- [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateDisabled];
- [weakSelf.sendYZMBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
- [weakSelf.sendYZMBtn setTitleColor:RGB(37, 138, 220) forState:UIControlStateNormal];
- });
- timeout--;
- }
- });
- dispatch_resume(_timer);
- }
-
- /****************************************************/
- #pragma mark - UITextFieldDelegate
- /****************************************************/
- - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
- // NSString *tempString = [textField.text stringByReplacingCharactersInRange:range withString:string];
- if ([string isEqualToString:@""] || [string isEqualToString:@"\n"]) {
- return YES;
- }
- NSString *regex = @"[\u4e00-\u9fa5]{0,}$"; // 中文
- NSPredicate *predicateRe1 = [NSPredicate predicateWithFormat:@"self matches %@", regex];
- // 3、匹配字符串
- BOOL resualt = [predicateRe1 evaluateWithObject:string];
- if (resualt)
- {
- return NO;
- }
- return YES;
- }
- - (void)textFieldDidEndEditing:(UITextField *)textField{
-
- }
- -(void)textFieldDidChange:(UITextField *)textField{
- if (textField.text.length > 20) {
- textField.text = [textField.text substringToIndex:20];
- }
- }
- -(void)dealloc{
- [[NSNotificationCenter defaultCenter] removeObserver:self name:WeiChatSuccess object:self];
- }
- // // 登录成功
- //USERDEFAULTSSET(@"tokenExpires",responseObject[@"expires"]);
- // NSString *token = [NSString stringWithFormat:@"%@ %@",responseObject[@"type"],responseObject[@"token"]];
- // USERDEFAULTSSET(@"token",token);
- // USERDEFAULTSSET(@"userId",responseObject[@"userId"]);
- // 22
- // expires = "2019-11-27 14:21:39";
- // token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjIyIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiVXNlciIsImV4cCI6MTU3NDgzNTY5OSwiaXNzIjoiaHR0cDovL3d3dy5HeFByZXNzLmNvbS5jbi8iLCJhdWQiOiJodHRwOi8vd3d3Lkd4UHJlc3MuY29tLmNuLyJ9.Z2os6jI9qxRGw0ovoX0TJe5W8KumQVGJRWyQNUqfSks";
- // type = Bearer;
- @end
|