《省钱达人》与《猎豆优选》UI相同版。域名tbk

DROldLoginViewController.m 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //
  2. // DRLoginViewController.m
  3. // YouHuiProject
  4. //
  5. // Created by 小花 on 2018/1/22.
  6. // Copyright © 2018年 kuxuan. All rights reserved.
  7. //
  8. #import "DRLoginViewController.h"
  9. #import "WLCaptcheButton.h"
  10. #import "DRSendCodeRequest.h"
  11. #import "DRLoginRequest.h"
  12. #import "WXApiManager.h"
  13. #import "TYAlertView.h"
  14. #import "UIView+TYAlertView.h"
  15. #import "TYAlertController.h"
  16. #import "DRLinkPhoneController.h"
  17. #import "DRLinkFansController.h"
  18. #import "DRLinkPhoneController.h"
  19. #import "DRUserInfo.h"
  20. #import "DROldLoginViewController.h"
  21. @interface DROldLoginViewController ()<WXApiManagerDelegate>
  22. @property (weak, nonatomic) IBOutlet UIImageView *iconImage;
  23. - (IBAction)closeAction:(id)sender;
  24. @property (weak, nonatomic) IBOutlet UIImageView *phoneIcon;
  25. @property (weak, nonatomic) IBOutlet UITextField *phoneField;
  26. @property (weak, nonatomic) IBOutlet UIImageView *codeIcon;
  27. @property (weak, nonatomic) IBOutlet WLCaptcheButton *codeBtn;
  28. @property (weak, nonatomic) IBOutlet UITextField *codeField;
  29. - (IBAction)userProtocol:(id)sender;
  30. - (IBAction)checkAction:(WLCaptcheButton *)sender;
  31. - (IBAction)loginAction:(id)sender;
  32. @property (weak, nonatomic) IBOutlet UIButton *loginBtn;
  33. - (IBAction)weChatLoginAction:(id)sender;
  34. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconTop;
  35. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneIconTop;
  36. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginBtnTOp;
  37. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *wxlabelTop;
  38. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *wxBtnTop;
  39. @property (weak, nonatomic) IBOutlet UIButton *weChatButton;
  40. @property(nonatomic,strong)AFHTTPSessionManager *manager;
  41. @property (nonatomic, strong) DRUserInfo *userInfo;
  42. @end
  43. @implementation DROldLoginViewController
  44. - (void)viewWillAppear:(BOOL)animated {
  45. [super viewWillAppear:animated];
  46. if (![PublicFunction isAvailableNetworkType]) {
  47. [MBProgressHUD showMessage:@"当前网络不可用"];
  48. }
  49. }
  50. - (void)viewDidLoad {
  51. [super viewDidLoad];
  52. [self updateConstraint];
  53. [self setDelegate];
  54. [self getAppIcon];
  55. [self addObserveForButtons];
  56. }
  57. - (void)updateConstraint {
  58. self.iconTop.constant *= SCREEN_MUTI;
  59. self.phoneIconTop.constant *= SCREEN_MUTI;
  60. self.loginBtnTOp.constant *= SCREEN_MUTI;
  61. self.wxlabelTop.constant *= SCREEN_MUTI;
  62. self.wxBtnTop.constant *= SCREEN_MUTI;
  63. if (![WXApi isWXAppInstalled]) {
  64. self.weChatButton.hidden = YES;
  65. }
  66. }
  67. - (void)setDelegate {
  68. [WXApiManager sharedManager].delegate = self;
  69. }
  70. - (void)getAppIcon {
  71. NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
  72. NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
  73. UIImage* image = [UIImage imageNamed:icon];
  74. self.iconImage.image = image;
  75. self.iconImage.layer.cornerRadius = 6;
  76. self.iconImage.layer.masksToBounds = YES;
  77. self.loginBtn.layer.cornerRadius = 20;
  78. self.codeBtn.layer.borderWidth = 1;
  79. self.codeBtn.layer.cornerRadius = 12;
  80. // self.codeBtn.disabledBackgroundColor = [UIColor YHColorWithHex:0xd8d8d8];
  81. }
  82. - (void)addObserveForButtons {
  83. RACSignal *textSingal = [self.phoneField.rac_textSignal map:^id(NSString * value) {
  84. return @(value.length >= 11);
  85. }];
  86. [textSingal subscribeNext:^(NSNumber *textActionSignal) {
  87. self.phoneIcon.image = [textActionSignal boolValue] ? [UIImage imageNamed:@"phone"]:[UIImage imageNamed:@"phone_gray"];
  88. self.codeBtn.backgroundColor = [textActionSignal boolValue] ? [UIColor whiteColor]:[UIColor YHColorWithHex:0xd8d8d8];
  89. self.codeBtn.layer.borderColor = [textActionSignal boolValue] ? [UIColor homeRedColor].CGColor:[UIColor YHColorWithHex:0xd8d8d8].CGColor;
  90. UIColor *color = [textActionSignal boolValue] ? [UIColor homeRedColor]:[UIColor whiteColor];
  91. [self.codeBtn setTitleColor:color forState:UIControlStateNormal];
  92. self.codeBtn.enabled = [textActionSignal boolValue];
  93. }];
  94. RACSignal *textSingal2 = [self.codeField.rac_textSignal map:^id(NSString * value) {
  95. return @(value.length > 0);
  96. }];
  97. [textSingal2 subscribeNext:^(NSNumber *textActionSignal) {
  98. self.codeIcon.image = [textActionSignal boolValue] ? [UIImage imageNamed:@"check_gray"]:[UIImage imageNamed:@"check_num"];
  99. }];
  100. RACSignal *calculActiveSignal = [RACSignal
  101. combineLatest:@[textSingal,
  102. textSingal2]
  103. reduce:^id(NSNumber *textValid, NSNumber *textValid2) {
  104. return @([textValid boolValue] && [textValid2 boolValue] );
  105. }];
  106. [calculActiveSignal subscribeNext:^(NSNumber *calculEnble) {
  107. self.loginBtn.enabled = [calculEnble boolValue];
  108. self.loginBtn.backgroundColor = [calculEnble boolValue] ? [UIColor homeRedColor] : [UIColor YHColorWithHex:0xd8d8d8];
  109. }];
  110. }
  111. - (void)didReceiveMemoryWarning {
  112. [super didReceiveMemoryWarning];
  113. // Dispose of any resources that can be recreated.
  114. }
  115. /**
  116. 关闭
  117. */
  118. - (IBAction)closeAction:(id)sender {
  119. [SVProgressHUD dismiss];
  120. [self dismissViewControllerAnimated:YES completion:nil];
  121. }
  122. /**
  123. 用户协议
  124. */
  125. - (IBAction)userProtocol:(id)sender {
  126. }
  127. /**
  128. 获取验证码
  129. */
  130. - (IBAction)checkAction:(WLCaptcheButton *)sender {
  131. NSString *ttl = [PublicFunction getNowTimeTimestamp];
  132. [self.codeField becomeFirstResponder];
  133. NSString *sign = [NSString stringWithFormat:@"phone=%@&ttl=%@%@",self.phoneField.text,ttl,SignCode];
  134. NSString *md5Str = [PublicFunction md5:sign];
  135. NSDictionary *para = @{@"phone":self.phoneField.text,
  136. @"ttl":ttl,
  137. @"sign":md5Str,
  138. };
  139. [DRSendCodeRequest post:Send_Code params:para success:^(id json) {
  140. if (json[@"success"]) {
  141. [sender fire];
  142. }
  143. } failure:^(NSError *error) {
  144. }];
  145. }
  146. /**
  147. 手机登录
  148. */
  149. - (IBAction)loginAction:(id)sender {
  150. NSDictionary *para = @{@"phone":self.phoneField.text,@"code":self.codeField.text,@"login_type":@"1"};
  151. NSString *url = [NSString stringWithFormat:@"%@%@",BaseURL,@"/api/v2/users/loginCodeNew"];
  152. [DRLoginRequest post:url params:para success:^(id json) {
  153. AccountModel *model = [AccountModel yy_modelWithJSON:json];
  154. [AccountTool saveAccount:model];
  155. NSString *sex = [NSString stringWithFormat:@"%@",json[@"data"][@"sex"]];
  156. [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
  157. [[NSUserDefaults standardUserDefaults] setObject:self.phoneField.text forKey:UserPhone];
  158. [[NSUserDefaults standardUserDefaults] synchronize];
  159. [[NSNotificationCenter defaultCenter] postNotificationName:ChangeSex object:nil];
  160. if (self.loginSucc) {
  161. self.loginSucc();
  162. }
  163. [self dismissViewControllerAnimated:YES completion:nil];
  164. } failure:^(NSError *error) {
  165. [MBProgressHUD showMessage:@"加载失败,请稍后重试"];
  166. }];
  167. }
  168. /**
  169. 微信登录
  170. */
  171. - (IBAction)weChatLoginAction:(id)sender {
  172. // [self sendReq];
  173. //登录前先取消友盟授权,友盟授权会带缓存
  174. [SVProgressHUD show];
  175. [[UMSocialManager defaultManager] cancelAuthWithPlatform:UMSocialPlatformType_WechatSession completion:^(id result, NSError *error) {
  176. if (error) {
  177. [SVProgressHUD dismiss];
  178. [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
  179. }
  180. [self getWechatAuthorInfo];
  181. }];
  182. }
  183. - (void)getWechatAuthorInfo {
  184. [[DRUMbindWeChat sharedInstance]loginWithPlatformSuccess:^(UMSocialUserInfoResponse *response) {
  185. if (response.openid && response.unionId && response.iconurl && response.name) {
  186. }else {
  187. [SVProgressHUD dismiss];
  188. [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
  189. return;
  190. }
  191. NSDictionary *para = @{@"openid":response.openid,
  192. @"unionid":response.unionId,
  193. @"nickname":response.name,
  194. @"headimgurl":response.iconurl
  195. };
  196. NSString *url = [NSString stringWithFormat:@"%@/api/v2/users/weChatLogin",BaseURL];
  197. [DRHttp post:url params:para success:^(id json) {
  198. if ([json[@"is_binded_mobile"] boolValue]) {
  199. //已绑定手机号
  200. AccountModel *model = [AccountModel yy_modelWithJSON:json];
  201. [AccountTool saveAccount:model];
  202. NSString *sex = [NSString stringWithFormat:@"%@",json[@"sex"]];
  203. [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
  204. [[NSUserDefaults standardUserDefaults] synchronize];
  205. if (self.loginSucc) {
  206. self.loginSucc();
  207. }
  208. [self dismissViewControllerAnimated:YES completion:nil];
  209. }else {
  210. //未绑定
  211. DRLinkPhoneController *linkPhone = [[DRLinkPhoneController alloc] init];
  212. [self dismissViewControllerAnimated:NO completion:nil];
  213. UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
  214. linkPhone.wx_union_id = response.unionId;
  215. if (self.loginSucc) {
  216. self.loginSucc();
  217. }
  218. [tabVC presentViewController:linkPhone animated:YES completion:^{
  219. }];
  220. }
  221. [self loadUserInfo];
  222. [SVProgressHUD dismiss];
  223. } failure:^(NSError *error) {
  224. [SVProgressHUD dismiss];
  225. [MBProgressHUD showMessage:@"加载失败"];
  226. }];
  227. } fail:^(NSError *error) {
  228. }];
  229. }
  230. /**
  231. 加载用户信息
  232. */
  233. - (void)loadUserInfo {
  234. if (![AccountTool isLogin]) {
  235. return;
  236. }
  237. [DRHttp post:UserInfo params:nil success:^(id json) {
  238. self.userInfo = [DRUserInfo yy_modelWithJSON:json];
  239. [[NSUserDefaults standardUserDefaults] setObject:self.userInfo.phone forKey:UserPhone];
  240. [[NSUserDefaults standardUserDefaults]synchronize];
  241. } failure:^(NSError *error) {
  242. }];
  243. }
  244. /**
  245. 微信登录发起授权
  246. */
  247. - (void)sendReq{
  248. SendAuthReq *req = [[SendAuthReq alloc] init];
  249. req.scope = @"snsapi_userinfo";
  250. req.state = @"App";
  251. [WXApi sendReq:req];
  252. }
  253. #pragma mark ------------- WXApiManagerDelegate -------------
  254. - (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
  255. // 授权成功
  256. if (response.errCode == 0) {
  257. // 获取用户信息
  258. [SVProgressHUD show];
  259. [self getWeChatTokenThenGetUserInfoWithCode:response.code];
  260. } else if (response.errCode == -2){
  261. TYAlertView *alert = [TYAlertView alertViewWithTitle:@"温馨提示" message:@"用户拒绝授权"];
  262. [alert addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:nil]];
  263. [alert showInController:self preferredStyle:TYAlertControllerStyleAlert];
  264. } else if (response.errCode == -2){
  265. TYAlertView *alert = [TYAlertView alertViewWithTitle:@"温馨提示" message:@"用户取消授权"];
  266. [alert addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:nil]];
  267. [alert showInController:self preferredStyle:TYAlertControllerStyleAlert];
  268. }
  269. }
  270. #pragma mark ------ prvate ----
  271. // 获取微信accesstoken
  272. - (void)getWeChatTokenThenGetUserInfoWithCode:(NSString *)code{
  273. NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WX_APPID,WX_APP_SECRET,code];
  274. [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  275. // responseDict 中含有 refresh_token,expires_in 超时时间
  276. id responseDict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
  277. NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseDict];
  278. // NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
  279. // [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*60*60]];
  280. // NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:[accessDict[@"expires_in"] intValue]];
  281. NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
  282. NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
  283. // NSString *refreshToken = [accessDict objectForKey:WX_Refresh_TOKEN];
  284. [self getWeChatUserInfoWithToken:accessToken andOpenID:openID];
  285. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  286. [SVProgressHUD showInfoWithStatus:@"请求失败"];
  287. }];
  288. }
  289. // 获取微信用户信息
  290. - (void)getWeChatUserInfoWithToken:(NSString *)token andOpenID:(NSString *)openid{
  291. // 通过access_token和openid获取用户信息
  292. NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openid];
  293. [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  294. id responseDict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
  295. [self wxLoginRequestWithResponseObject:responseDict];
  296. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  297. [SVProgressHUD showInfoWithStatus:@"请求失败"];
  298. }];
  299. }
  300. - (void)wxLoginRequestWithResponseObject:(id)responseObject {
  301. if (responseObject[@"openid"] && responseObject[@"unionid"] && responseObject[@"nickname"] && responseObject[@"headimgurl"]) {
  302. }else {
  303. [SVProgressHUD dismiss];
  304. [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
  305. return;
  306. }
  307. NSDictionary *para = @{@"openid":responseObject[@"openid"],
  308. @"unionid":responseObject[@"unionid"],
  309. @"nickname":responseObject[@"nickname"],
  310. @"headimgurl":responseObject[@"headimgurl"]
  311. };
  312. NSString *url = [NSString stringWithFormat:@"%@/api/v2/users/weChatLogin",BaseURL];
  313. [DRHttp post:url params:para success:^(id json) {
  314. if ([json[@"is_binded_mobile"] boolValue]) {
  315. //已绑定手机号
  316. AccountModel *model = [AccountModel yy_modelWithJSON:json];
  317. [AccountTool saveAccount:model];
  318. NSString *sex = [NSString stringWithFormat:@"%@",json[@"sex"]];
  319. [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
  320. [[NSUserDefaults standardUserDefaults] synchronize];
  321. [self dismissViewControllerAnimated:YES completion:nil];
  322. }else {
  323. //未绑定
  324. DRLinkPhoneController *linkPhone = [[DRLinkPhoneController alloc] init];
  325. [self dismissViewControllerAnimated:NO completion:nil];
  326. UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
  327. linkPhone.wx_union_id = responseObject[@"unionid"];
  328. [tabVC presentViewController:linkPhone animated:YES completion:^{
  329. }];
  330. }
  331. [SVProgressHUD dismiss];
  332. } failure:^(NSError *error) {
  333. [SVProgressHUD dismiss];
  334. [MBProgressHUD showMessage:@"请求失败"];
  335. }];
  336. }
  337. #pragma mark ----- layzer -----
  338. - (AFHTTPSessionManager *)manager{
  339. if (!_manager) {
  340. _manager = [AFHTTPSessionManager manager];
  341. _manager.requestSerializer.timeoutInterval = 15;
  342. _manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 解析为data
  343. _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
  344. _manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
  345. }
  346. return _manager;
  347. }
  348. @end