口袋优选

KBOldLoginViewController.m 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //
  2. // KBLoginViewController.m
  3. // YouHuiProject
  4. //
  5. // Created by 小花 on 2018/1/22.
  6. // Copyright © 2018年 kuxuan. All rights reserved.
  7. //
  8. #import "KBLoginViewController.h"
  9. #import "WLCaptcheButton.h"
  10. #import "KBSendCodeRequest.h"
  11. #import "KBLoginRequest.h"
  12. #import "WXApiManager.h"
  13. #import "TYAlertView.h"
  14. #import "UIView+TYAlertView.h"
  15. #import "TYAlertController.h"
  16. #import "KBLinkPhoneController.h"
  17. #import "KBLinkFansController.h"
  18. #import "KBLinkPhoneController.h"
  19. #import "KBUserInfo.h"
  20. #import "KBOldLoginViewController.h"
  21. @interface KBOldLoginViewController ()<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) KBUserInfo *userInfo;
  42. @end
  43. @implementation KBOldLoginViewController
  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. [KBSendCodeRequest 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. [KBLoginRequest post:ValidLoginAPI params:para success:^(id json) {
  152. AccountModel *model = [AccountModel yy_modelWithJSON:json];
  153. [AccountTool saveAccount:model];
  154. NSString *sex = [NSString stringWithFormat:@"%@",json[@"data"][@"sex"]];
  155. [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
  156. [[NSUserDefaults standardUserDefaults] setObject:self.phoneField.text forKey:UserPhone];
  157. [[NSUserDefaults standardUserDefaults] synchronize];
  158. [[NSNotificationCenter defaultCenter] postNotificationName:ChangeSex object:nil];
  159. if (self.loginSucc) {
  160. self.loginSucc();
  161. }
  162. [self dismissViewControllerAnimated:YES completion:nil];
  163. } failure:^(NSError *error) {
  164. [MBProgressHUD showMessage:@"加载失败,请稍后重试"];
  165. }];
  166. }
  167. /**
  168. 微信登录
  169. */
  170. - (IBAction)weChatLoginAction:(id)sender {
  171. // [self sendReq];
  172. //登录前先取消友盟授权,友盟授权会带缓存
  173. [SVProgressHUD show];
  174. [[UMSocialManager defaultManager] cancelAuthWithPlatform:UMSocialPlatformType_WechatSession completion:^(id result, NSError *error) {
  175. if (error) {
  176. [SVProgressHUD dismiss];
  177. [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
  178. }
  179. [self getWechatAuthorInfo];
  180. }];
  181. }
  182. - (void)getWechatAuthorInfo {
  183. [[KBUMbindWeChat sharedInstance]loginWithPlatformSuccess:^(UMSocialUserInfoResponse *response) {
  184. if (response.openid && response.unionId && response.iconurl && response.name) {
  185. }else {
  186. [SVProgressHUD dismiss];
  187. [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
  188. return;
  189. }
  190. NSDictionary *para = @{@"openid":response.openid,
  191. @"unionid":response.unionId,
  192. @"nickname":response.name,
  193. @"headimgurl":response.iconurl
  194. };
  195. NSString *url = [NSString stringWithFormat:@"%@/api/v2/users/weChatLogin",BaseURL];
  196. [KBHttp post:url params:para success:^(id json) {
  197. if ([json[@"is_binded_mobile"] boolValue]) {
  198. //已绑定手机号
  199. AccountModel *model = [AccountModel yy_modelWithJSON:json];
  200. [AccountTool saveAccount:model];
  201. NSString *sex = [NSString stringWithFormat:@"%@",json[@"sex"]];
  202. [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
  203. [[NSUserDefaults standardUserDefaults] synchronize];
  204. if (self.loginSucc) {
  205. self.loginSucc();
  206. }
  207. [self dismissViewControllerAnimated:YES completion:nil];
  208. }else {
  209. //未绑定
  210. KBLinkPhoneController *linkPhone = [[KBLinkPhoneController alloc] init];
  211. [self dismissViewControllerAnimated:NO completion:nil];
  212. UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
  213. linkPhone.wx_union_id = response.unionId;
  214. if (self.loginSucc) {
  215. self.loginSucc();
  216. }
  217. [tabVC presentViewController:linkPhone animated:YES completion:^{
  218. }];
  219. }
  220. [self loadUserInfo];
  221. [SVProgressHUD dismiss];
  222. } failure:^(NSError *error) {
  223. [SVProgressHUD dismiss];
  224. [MBProgressHUD showMessage:@"加载失败"];
  225. }];
  226. } fail:^(NSError *error) {
  227. }];
  228. }
  229. /**
  230. 加载用户信息
  231. */
  232. - (void)loadUserInfo {
  233. if (![AccountTool isLogin]) {
  234. return;
  235. }
  236. [KBHttp post:UserInfo params:nil success:^(id json) {
  237. self.userInfo = [KBUserInfo yy_modelWithJSON:json];
  238. [[NSUserDefaults standardUserDefaults] setObject:self.userInfo.phone forKey:UserPhone];
  239. [[NSUserDefaults standardUserDefaults]synchronize];
  240. } failure:^(NSError *error) {
  241. }];
  242. }
  243. /**
  244. 微信登录发起授权
  245. */
  246. - (void)sendReq{
  247. SendAuthReq *req = [[SendAuthReq alloc] init];
  248. req.scope = @"snsapi_userinfo";
  249. req.state = @"App";
  250. [WXApi sendReq:req];
  251. }
  252. #pragma mark ------------- WXApiManagerDelegate -------------
  253. - (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
  254. // 授权成功
  255. if (response.errCode == 0) {
  256. // 获取用户信息
  257. [SVProgressHUD show];
  258. [self getWeChatTokenThenGetUserInfoWithCode:response.code];
  259. } else if (response.errCode == -2){
  260. TYAlertView *alert = [TYAlertView alertViewWithTitle:@"温馨提示" message:@"用户拒绝授权"];
  261. [alert addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:nil]];
  262. [alert showInController:self preferredStyle:TYAlertControllerStyleAlert];
  263. } else if (response.errCode == -2){
  264. TYAlertView *alert = [TYAlertView alertViewWithTitle:@"温馨提示" message:@"用户取消授权"];
  265. [alert addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:nil]];
  266. [alert showInController:self preferredStyle:TYAlertControllerStyleAlert];
  267. }
  268. }
  269. #pragma mark ------ prvate ----
  270. // 获取微信accesstoken
  271. - (void)getWeChatTokenThenGetUserInfoWithCode:(NSString *)code{
  272. 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];
  273. [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  274. // responseDict 中含有 refresh_token,expires_in 超时时间
  275. id responseDict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
  276. NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseDict];
  277. // NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
  278. // [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*60*60]];
  279. // NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:[accessDict[@"expires_in"] intValue]];
  280. NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
  281. NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
  282. // NSString *refreshToken = [accessDict objectForKey:WX_Refresh_TOKEN];
  283. [self getWeChatUserInfoWithToken:accessToken andOpenID:openID];
  284. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  285. [SVProgressHUD showInfoWithStatus:@"请求失败"];
  286. }];
  287. }
  288. // 获取微信用户信息
  289. - (void)getWeChatUserInfoWithToken:(NSString *)token andOpenID:(NSString *)openid{
  290. // 通过access_token和openid获取用户信息
  291. NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openid];
  292. [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  293. id responseDict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
  294. [self wxLoginRequestWithResponseObject:responseDict];
  295. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  296. [SVProgressHUD showInfoWithStatus:@"请求失败"];
  297. }];
  298. }
  299. - (void)wxLoginRequestWithResponseObject:(id)responseObject {
  300. if (responseObject[@"openid"] && responseObject[@"unionid"] && responseObject[@"nickname"] && responseObject[@"headimgurl"]) {
  301. }else {
  302. [SVProgressHUD dismiss];
  303. [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
  304. return;
  305. }
  306. NSDictionary *para = @{@"openid":responseObject[@"openid"],
  307. @"unionid":responseObject[@"unionid"],
  308. @"nickname":responseObject[@"nickname"],
  309. @"headimgurl":responseObject[@"headimgurl"]
  310. };
  311. NSString *url = [NSString stringWithFormat:@"%@/api/v2/users/weChatLogin",BaseURL];
  312. [KBHttp post:url params:para success:^(id json) {
  313. if ([json[@"is_binded_mobile"] boolValue]) {
  314. //已绑定手机号
  315. AccountModel *model = [AccountModel yy_modelWithJSON:json];
  316. [AccountTool saveAccount:model];
  317. NSString *sex = [NSString stringWithFormat:@"%@",json[@"sex"]];
  318. [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
  319. [[NSUserDefaults standardUserDefaults] synchronize];
  320. [self dismissViewControllerAnimated:YES completion:nil];
  321. }else {
  322. //未绑定
  323. KBLinkPhoneController *linkPhone = [[KBLinkPhoneController alloc] init];
  324. [self dismissViewControllerAnimated:NO completion:nil];
  325. UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
  326. linkPhone.wx_union_id = responseObject[@"unionid"];
  327. [tabVC presentViewController:linkPhone animated:YES completion:^{
  328. }];
  329. }
  330. [SVProgressHUD dismiss];
  331. } failure:^(NSError *error) {
  332. [SVProgressHUD dismiss];
  333. [MBProgressHUD showMessage:@"请求失败"];
  334. }];
  335. }
  336. #pragma mark ----- layzer -----
  337. - (AFHTTPSessionManager *)manager{
  338. if (!_manager) {
  339. _manager = [AFHTTPSessionManager manager];
  340. _manager.requestSerializer.timeoutInterval = 15;
  341. _manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 解析为data
  342. _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
  343. _manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
  344. }
  345. return _manager;
  346. }
  347. @end