LoginVC.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //
  2. // LoginVC.m
  3. // smartRhino
  4. //
  5. // Created by armin on 2019/11/2.
  6. // Copyright © 2019 tederen. All rights reserved.
  7. //
  8. #import "LoginVC.h"
  9. #import "TabBarController.h"
  10. #import "WXApi.h"
  11. #import "EditPhoneOrEmailVC.h"
  12. @interface LoginVC ()<UITextFieldDelegate>
  13. //可滚动区域H
  14. @property (strong,nonatomic) IBOutlet NSLayoutConstraint *scrollH;
  15. @property (strong,nonatomic) IBOutlet UITextField *phoneTextField;
  16. @property (strong,nonatomic) IBOutlet UIButton *sendYZMBtn;
  17. @property (strong,nonatomic) IBOutlet UITextField *yzmTextField;
  18. @property (strong,nonatomic) IBOutlet UIButton *loginBtn;
  19. @property (strong,nonatomic) IBOutlet UIButton *wechatBtn;
  20. @end
  21. @implementation LoginVC
  22. +(LoginVC *)initLoginVC{
  23. LoginVC *controller = [StoryboardManager.shared.login instantiateViewControllerWithIdentifier:@"LoginVC"];
  24. return controller;
  25. }
  26. - (void)viewDidLoad {
  27. [super viewDidLoad];
  28. self.fd_prefersNavigationBarHidden = YES;
  29. self.phoneTextField.text = @"";
  30. self.phoneTextField.delegate = self;
  31. self.phoneTextField.placeholder = @"请输入手机号";
  32. self.phoneTextField.textColor = RGB(51, 51, 51);
  33. [self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  34. Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
  35. UILabel *placeholderLabel = object_getIvar(self.phoneTextField, ivar);
  36. placeholderLabel.textColor = RGB(153, 153, 153);
  37. [self.sendYZMBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
  38. self.yzmTextField.text = @"";
  39. self.yzmTextField.delegate = self;
  40. self.yzmTextField.placeholder = @"请输入验证码";
  41. self.yzmTextField.textColor = RGB(51, 51, 51);
  42. [self.yzmTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  43. Ivar ivart = class_getInstanceVariable([UITextField class], "_placeholderLabel");
  44. UILabel *placeholderLabelt = object_getIvar(self.yzmTextField, ivart);
  45. placeholderLabelt.textColor = RGB(153, 153, 153);
  46. self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
  47. self.yzmTextField.keyboardType = UIKeyboardTypeNumberPad;
  48. self.loginBtn.layer.masksToBounds = YES;
  49. self.loginBtn.layer.cornerRadius = 8.0;
  50. WS(weakSelf);
  51. [self.loginBtn setAction:^{
  52. [weakSelf gotoLogin:@""];
  53. // [weakSelf changeToHome];
  54. }];
  55. [self.wechatBtn setAction:^{
  56. [weakSelf sendWXAuthReq];
  57. }];
  58. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiChatOK:) name:WeiChatSuccess object:NULL];
  59. }
  60. #pragma mark - 微信登录成功回调信息
  61. - (void)sendWXAuthReq{//复制即可
  62. if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
  63. SendAuthReq *req = [[SendAuthReq alloc] init];
  64. req.state = @"wx_oauth_authorization_state";//用于保持请求和回调的状态,授权请求或原样带回
  65. req.scope = @"snsapi_userinfo";//授权作用域:获取用户个人信息
  66. //唤起微信
  67. [WXApi sendReq:req];
  68. }else{
  69. SHOWERROR(@"未安装微信应用或版本过低");
  70. }
  71. }
  72. -(void)weiChatOK:(NSNotification *)noti
  73. {
  74. WS(weakSelf);
  75. NSLog(@"^^^^^^^^%@",noti.userInfo);
  76. NSDictionary * dic = noti.userInfo;
  77. NSString * url = [NSString stringWithFormat:@"%@%@",Host(API_App_User_Opend_Id),dic[@"openid"]];
  78. [[HttpManager sharedHttpManager] GETUrl:url parameters:@{} responseStyle:DATA success:^(id _Nonnull responseObject) {
  79. NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  80. BOOL isOpenId = [str boolValue];
  81. if (isOpenId) {
  82. [weakSelf gotoLogin:dic[@"openid"]];
  83. }else{
  84. EditPhoneOrEmailVC *vc = [EditPhoneOrEmailVC initEditPhoneOrEmailVC];
  85. vc.pageType = BindingOrChangePhoneOrEmailPageType5;
  86. vc.openId = dic[@"openid"];
  87. [self.navigationController pushViewController:vc animated:NO];
  88. }
  89. } failure:^(NSError * _Nonnull error) {
  90. }];
  91. }
  92. - (void)gotoLogin:(NSString *)openId{
  93. if (openId.length == 0) {
  94. if (self.phoneTextField.text.length != 11) {
  95. SHOWERROR(@"请输入正确的手机号码")
  96. return;
  97. }
  98. if (self.yzmTextField.text.length != 6) {
  99. SHOWERROR(@"请输入正确的验证码")
  100. return;
  101. }
  102. }
  103. SHOWLOADING
  104. WEAKSELF
  105. NSLog(@"⚠️ 手机号码 %@ 登录验证码%@",self.phoneTextField.text,self.yzmTextField.text);
  106. [[HttpManager sharedHttpManager] POSTUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,LoginPost] parameters:@{@"phone":self.phoneTextField.text,@"code":self.yzmTextField.text,@"OpenId":openId} responseStyle:JOSN success:^(id _Nonnull responseObject) {
  107. NSLog(@"响应结果 %@",responseObject);
  108. NSDictionary *dic = responseObject;
  109. USERDEFAULTSSET(dic[@"Token"][@"Expires"],@"tokenExpires");
  110. NSString *token = [NSString stringWithFormat:@"%@ %@",dic[@"Token"][@"Type"],dic[@"Token"][@"Token"]];
  111. USERDEFAULTSSET(token,@"LOGINTOKEN");
  112. NSLog(@"登录成功之后的token%@\n%@",kToken,token);
  113. USERDEFAULTSSET(dic[@"UserId"],@"userId");
  114. REMOVESHOW
  115. [weakSelf getUserInfoDetail];
  116. } failure:^(NSError * _Nonnull error) {
  117. REMOVESHOW
  118. SHOWERROR([ZYCTool handerResultData:error])
  119. }];
  120. }
  121. - (void)getUserInfoDetail{
  122. SHOWLOADING
  123. WEAKSELF
  124. NSLog(@"%@",kUserId);
  125. [[HttpManager sharedHttpManager].manager.requestSerializer setValue:[UserManager token] forHTTPHeaderField:@"Authorization"];
  126. [[HttpManager sharedHttpManager] GETUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,UserDetailGet] parameters:@{} success:^(id _Nonnull responseObject) {
  127. NSLog(@"%@",responseObject);
  128. AppUserModel * model = [[AppUserModel alloc] initWithDictionary:responseObject error:nil];
  129. [model saveUserInfor];
  130. REMOVESHOW
  131. NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
  132. USERDEFAULTSSET(data,@"USERINFO");
  133. //在这里登陆环信
  134. [[EMClient sharedClient] loginWithUsername:@"13699447785" password:@"123456" completion:^(NSString *aUsername, EMError *aError) {
  135. EMError *error = aError;
  136. dispatch_async(dispatch_get_main_queue(), ^{
  137. if (!error) {
  138. //设置是否自动登录
  139. [[EMClient sharedClient].options setIsAutoLogin:YES];
  140. [weakSelf changeToHome];
  141. } else {
  142. [weakSelf changeToLogin];
  143. NSLog(@"emclient login error:%u",error.code);
  144. switch (error.code)
  145. {
  146. case EMErrorUserNotFound:
  147. SHOWERROR(@"用户不存在");
  148. break;
  149. case EMErrorNetworkUnavailable:
  150. break;
  151. case EMErrorServerNotReachable:
  152. break;
  153. case EMErrorUserAuthenticationFailed:
  154. break;
  155. case EMErrorServerTimeout:
  156. break;
  157. case EMErrorServerServingForbidden:
  158. break;
  159. case EMErrorInvalidUsername:
  160. SHOWERROR(@"用户名无效");
  161. break;
  162. case EMErrorUserLoginTooManyDevices:
  163. break;
  164. case EMErrorUserNotLogin:
  165. SHOWERROR(@"用户未登陆");
  166. break;
  167. default:
  168. break;
  169. }
  170. }
  171. });
  172. }];
  173. } failure:^(NSError * _Nonnull error) {
  174. REMOVESHOW
  175. SHOWERROR([ZYCTool handerResultData:error])
  176. }];
  177. }
  178. -(void)changeToLogin{
  179. [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"LOGINTOKEN"];
  180. [[NSUserDefaults standardUserDefaults] synchronize];
  181. [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
  182. [[HttpManager sharedHttpManager].manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
  183. }];
  184. }
  185. -(void)changeToHome{
  186. UIWindow *window = [UtilsTools getWindow];
  187. window.rootViewController = [TabBarController sharedTabBarController];
  188. [[TabBarController sharedTabBarController] setSelectedIndex:0];
  189. [window makeKeyAndVisible];
  190. }
  191. - (IBAction)verifyCodeAction:(UIButton *)sender {
  192. [self.view endEditing:YES];
  193. // [sender setEnabled:NO];
  194. if (self.phoneTextField.text.length != 11) {
  195. SHOWERROR(@"请输入正确的手机号码")
  196. return;
  197. }
  198. NSLog(@"⚠️ 登陆获取验证码 %@",self.phoneTextField.text);
  199. SHOWLOADING
  200. [[HttpManager sharedHttpManager] GETUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,LoginSendCodeGet] parameters:@{@"phone":self.phoneTextField.text} responseStyle:DATA success:^(id _Nonnull responseObject) {
  201. REMOVESHOW
  202. [self startTime];
  203. } failure:^(NSError * _Nonnull error) {
  204. REMOVESHOW
  205. SHOWERROR([ZYCTool handerResultData:error])
  206. }];
  207. // [[HttpManager sharedHttpManager] GET:[NSString stringWithFormat:@"%@%@",BaseUrl,LoginSendCodeGet] parameters:@{@"phone":self.phoneTextField.text} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  208. //
  209. // REMOVESHOW
  210. // [self startTime];
  211. // } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  212. // REMOVESHOW
  213. //
  214. // SHOWERROR([ZYCTool handerResultData:error])
  215. // }];
  216. }
  217. -(void)startTime{
  218. __block int timeout=60; //倒计时时间
  219. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  220. dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
  221. dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
  222. dispatch_source_set_event_handler(_timer, ^{
  223. if(timeout<=0){ //倒计时结束,关闭
  224. dispatch_source_cancel(_timer);
  225. WS(weakSelf);
  226. dispatch_async(dispatch_get_main_queue(), ^{
  227. //设置界面的按钮显示 根据自己需求设置 特别注明:UI的改变一定要在主线程中进行
  228. //倒计时完成,恢复到原来的效果
  229. weakSelf.sendYZMBtn.enabled = YES;
  230. NSString *text = @"获取验证码";
  231. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateNormal];
  232. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateHighlighted];
  233. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateSelected];
  234. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateDisabled];
  235. [weakSelf.sendYZMBtn setTitleColor:RGB(37, 138, 220) forState:UIControlStateNormal];
  236. [weakSelf.sendYZMBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
  237. [weakSelf.sendYZMBtn setEnabled:YES];
  238. });
  239. }else{
  240. int seconds = timeout % 60;
  241. if(seconds == 0&&timeout==60){
  242. seconds = 60;
  243. }
  244. // NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
  245. WS(weakSelf);
  246. dispatch_async(dispatch_get_main_queue(), ^{
  247. //设置界面的按钮显示 根据自己需求设置
  248. // NSLog(@"____%@",strTime);
  249. weakSelf.sendYZMBtn.enabled = NO;
  250. NSString *text = [NSString stringWithFormat:@"重新获取(%lus)",(unsigned long)seconds];
  251. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateNormal];
  252. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateHighlighted];
  253. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateSelected];
  254. [weakSelf.sendYZMBtn setTitle:text forState:UIControlStateDisabled];
  255. [weakSelf.sendYZMBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
  256. [weakSelf.sendYZMBtn setTitleColor:RGB(37, 138, 220) forState:UIControlStateNormal];
  257. });
  258. timeout--;
  259. }
  260. });
  261. dispatch_resume(_timer);
  262. }
  263. /****************************************************/
  264. #pragma mark - UITextFieldDelegate
  265. /****************************************************/
  266. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
  267. // NSString *tempString = [textField.text stringByReplacingCharactersInRange:range withString:string];
  268. if ([string isEqualToString:@""] || [string isEqualToString:@"\n"]) {
  269. return YES;
  270. }
  271. NSString *regex = @"[\u4e00-\u9fa5]{0,}$"; // 中文
  272. NSPredicate *predicateRe1 = [NSPredicate predicateWithFormat:@"self matches %@", regex];
  273. // 3、匹配字符串
  274. BOOL resualt = [predicateRe1 evaluateWithObject:string];
  275. if (resualt)
  276. {
  277. return NO;
  278. }
  279. return YES;
  280. }
  281. - (void)textFieldDidEndEditing:(UITextField *)textField{
  282. }
  283. -(void)textFieldDidChange:(UITextField *)textField{
  284. if (textField.text.length > 20) {
  285. textField.text = [textField.text substringToIndex:20];
  286. }
  287. }
  288. -(void)dealloc{
  289. [[NSNotificationCenter defaultCenter] removeObserver:self name:WeiChatSuccess object:self];
  290. }
  291. // // 登录成功
  292. //USERDEFAULTSSET(@"tokenExpires",responseObject[@"expires"]);
  293. // NSString *token = [NSString stringWithFormat:@"%@ %@",responseObject[@"type"],responseObject[@"token"]];
  294. // USERDEFAULTSSET(@"token",token);
  295. // USERDEFAULTSSET(@"userId",responseObject[@"userId"]);
  296. // 22
  297. // expires = "2019-11-27 14:21:39";
  298. // token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjIyIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiVXNlciIsImV4cCI6MTU3NDgzNTY5OSwiaXNzIjoiaHR0cDovL3d3dy5HeFByZXNzLmNvbS5jbi8iLCJhdWQiOiJodHRwOi8vd3d3Lkd4UHJlc3MuY29tLmNuLyJ9.Z2os6jI9qxRGw0ovoX0TJe5W8KumQVGJRWyQNUqfSks";
  299. // type = Bearer;
  300. @end