123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435 |
- //
- // KBLoginViewController.m
- // YouHuiProject
- //
- // Created by 小花 on 2018/1/22.
- // Copyright © 2018年 kuxuan. All rights reserved.
- //
- #import "KBLoginViewController.h"
- #import "WLCaptcheButton.h"
- #import "KBSendCodeRequest.h"
- #import "KBLoginRequest.h"
- #import "WXApiManager.h"
- #import "TYAlertView.h"
- #import "UIView+TYAlertView.h"
- #import "TYAlertController.h"
- #import "KBLinkPhoneController.h"
- #import "KBLinkFansController.h"
- #import "KBLinkPhoneController.h"
- #import "KBUserInfo.h"
- #import "KBOldLoginViewController.h"
- @interface KBOldLoginViewController ()<WXApiManagerDelegate>
- @property (weak, nonatomic) IBOutlet UIImageView *iconImage;
- - (IBAction)closeAction:(id)sender;
- @property (weak, nonatomic) IBOutlet UIImageView *phoneIcon;
- @property (weak, nonatomic) IBOutlet UITextField *phoneField;
- @property (weak, nonatomic) IBOutlet UIImageView *codeIcon;
- @property (weak, nonatomic) IBOutlet WLCaptcheButton *codeBtn;
- @property (weak, nonatomic) IBOutlet UITextField *codeField;
- - (IBAction)userProtocol:(id)sender;
- - (IBAction)checkAction:(WLCaptcheButton *)sender;
- - (IBAction)loginAction:(id)sender;
- @property (weak, nonatomic) IBOutlet UIButton *loginBtn;
- - (IBAction)weChatLoginAction:(id)sender;
- @property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconTop;
- @property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneIconTop;
- @property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginBtnTOp;
- @property (weak, nonatomic) IBOutlet NSLayoutConstraint *wxlabelTop;
- @property (weak, nonatomic) IBOutlet NSLayoutConstraint *wxBtnTop;
- @property (weak, nonatomic) IBOutlet UIButton *weChatButton;
- @property(nonatomic,strong)AFHTTPSessionManager *manager;
- @property (nonatomic, strong) KBUserInfo *userInfo;
- @end
- @implementation KBOldLoginViewController
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- if (![PublicFunction isAvailableNetworkType]) {
- [MBProgressHUD showMessage:@"当前网络不可用"];
- }
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
-
- [self updateConstraint];
- [self setDelegate];
- [self getAppIcon];
- [self addObserveForButtons];
- }
- - (void)updateConstraint {
- self.iconTop.constant *= SCREEN_MUTI;
- self.phoneIconTop.constant *= SCREEN_MUTI;
- self.loginBtnTOp.constant *= SCREEN_MUTI;
- self.wxlabelTop.constant *= SCREEN_MUTI;
- self.wxBtnTop.constant *= SCREEN_MUTI;
-
- if (![WXApi isWXAppInstalled]) {
- self.weChatButton.hidden = YES;
- }
- }
- - (void)setDelegate {
- [WXApiManager sharedManager].delegate = self;
- }
- - (void)getAppIcon {
- NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
-
- NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
-
- UIImage* image = [UIImage imageNamed:icon];
- self.iconImage.image = image;
- self.iconImage.layer.cornerRadius = 6;
- self.iconImage.layer.masksToBounds = YES;
-
-
- self.loginBtn.layer.cornerRadius = 20;
-
- self.codeBtn.layer.borderWidth = 1;
-
- self.codeBtn.layer.cornerRadius = 12;
- // self.codeBtn.disabledBackgroundColor = [UIColor YHColorWithHex:0xd8d8d8];
- }
- - (void)addObserveForButtons {
- RACSignal *textSingal = [self.phoneField.rac_textSignal map:^id(NSString * value) {
- return @(value.length >= 11);
- }];
- [textSingal subscribeNext:^(NSNumber *textActionSignal) {
- self.phoneIcon.image = [textActionSignal boolValue] ? [UIImage imageNamed:@"phone"]:[UIImage imageNamed:@"phone_gray"];
- self.codeBtn.backgroundColor = [textActionSignal boolValue] ? [UIColor whiteColor]:[UIColor YHColorWithHex:0xd8d8d8];
- self.codeBtn.layer.borderColor = [textActionSignal boolValue] ? [UIColor homeRedColor].CGColor:[UIColor YHColorWithHex:0xd8d8d8].CGColor;
-
- UIColor *color = [textActionSignal boolValue] ? [UIColor homeRedColor]:[UIColor whiteColor];
- [self.codeBtn setTitleColor:color forState:UIControlStateNormal];
- self.codeBtn.enabled = [textActionSignal boolValue];
- }];
-
- RACSignal *textSingal2 = [self.codeField.rac_textSignal map:^id(NSString * value) {
- return @(value.length > 0);
- }];
- [textSingal2 subscribeNext:^(NSNumber *textActionSignal) {
- self.codeIcon.image = [textActionSignal boolValue] ? [UIImage imageNamed:@"check_gray"]:[UIImage imageNamed:@"check_num"];
- }];
-
- RACSignal *calculActiveSignal = [RACSignal
- combineLatest:@[textSingal,
- textSingal2]
- reduce:^id(NSNumber *textValid, NSNumber *textValid2) {
- return @([textValid boolValue] && [textValid2 boolValue] );
- }];
-
- [calculActiveSignal subscribeNext:^(NSNumber *calculEnble) {
- self.loginBtn.enabled = [calculEnble boolValue];
- self.loginBtn.backgroundColor = [calculEnble boolValue] ? [UIColor homeRedColor] : [UIColor YHColorWithHex:0xd8d8d8];
- }];
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- /**
- 关闭
- */
- - (IBAction)closeAction:(id)sender {
- [SVProgressHUD dismiss];
- [self dismissViewControllerAnimated:YES completion:nil];
- }
- /**
- 用户协议
- */
- - (IBAction)userProtocol:(id)sender {
- }
- /**
- 获取验证码
- */
- - (IBAction)checkAction:(WLCaptcheButton *)sender {
-
- NSString *ttl = [PublicFunction getNowTimeTimestamp];
- [self.codeField becomeFirstResponder];
-
- NSString *sign = [NSString stringWithFormat:@"phone=%@&ttl=%@%@",self.phoneField.text,ttl,SignCode];
- NSString *md5Str = [PublicFunction md5:sign];
- NSDictionary *para = @{@"phone":self.phoneField.text,
- @"ttl":ttl,
- @"sign":md5Str,
- };
- [KBSendCodeRequest post:Send_Code params:para success:^(id json) {
- if (json[@"success"]) {
- [sender fire];
- }
- } failure:^(NSError *error) {
-
- }];
- }
- /**
- 手机登录
- */
- - (IBAction)loginAction:(id)sender {
-
- NSDictionary *para = @{@"phone":self.phoneField.text,@"code":self.codeField.text,@"login_type":@"1"};
-
- [KBLoginRequest post:ValidLoginAPI params:para success:^(id json) {
-
- AccountModel *model = [AccountModel yy_modelWithJSON:json];
- [AccountTool saveAccount:model];
- NSString *sex = [NSString stringWithFormat:@"%@",json[@"data"][@"sex"]];
- [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
- [[NSUserDefaults standardUserDefaults] setObject:self.phoneField.text forKey:UserPhone];
- [[NSUserDefaults standardUserDefaults] synchronize];
- [[NSNotificationCenter defaultCenter] postNotificationName:ChangeSex object:nil];
- if (self.loginSucc) {
- self.loginSucc();
- }
- [self dismissViewControllerAnimated:YES completion:nil];
-
- } failure:^(NSError *error) {
- [MBProgressHUD showMessage:@"加载失败,请稍后重试"];
- }];
-
- }
- /**
- 微信登录
- */
- - (IBAction)weChatLoginAction:(id)sender {
- // [self sendReq];
-
- //登录前先取消友盟授权,友盟授权会带缓存
- [SVProgressHUD show];
- [[UMSocialManager defaultManager] cancelAuthWithPlatform:UMSocialPlatformType_WechatSession completion:^(id result, NSError *error) {
- if (error) {
- [SVProgressHUD dismiss];
- [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
- }
- [self getWechatAuthorInfo];
- }];
-
-
- }
- - (void)getWechatAuthorInfo {
- [[KBUMbindWeChat sharedInstance]loginWithPlatformSuccess:^(UMSocialUserInfoResponse *response) {
- if (response.openid && response.unionId && response.iconurl && response.name) {
-
- }else {
- [SVProgressHUD dismiss];
- [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
- return;
- }
- NSDictionary *para = @{@"openid":response.openid,
- @"unionid":response.unionId,
- @"nickname":response.name,
- @"headimgurl":response.iconurl
- };
- NSString *url = [NSString stringWithFormat:@"%@/api/v2/users/weChatLogin",BaseURL];
- [KBHttp post:url params:para success:^(id json) {
-
-
-
- if ([json[@"is_binded_mobile"] boolValue]) {
- //已绑定手机号
- AccountModel *model = [AccountModel yy_modelWithJSON:json];
- [AccountTool saveAccount:model];
- NSString *sex = [NSString stringWithFormat:@"%@",json[@"sex"]];
- [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
- [[NSUserDefaults standardUserDefaults] synchronize];
- if (self.loginSucc) {
- self.loginSucc();
- }
- [self dismissViewControllerAnimated:YES completion:nil];
- }else {
- //未绑定
- KBLinkPhoneController *linkPhone = [[KBLinkPhoneController alloc] init];
- [self dismissViewControllerAnimated:NO completion:nil];
- UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
- linkPhone.wx_union_id = response.unionId;
- if (self.loginSucc) {
- self.loginSucc();
- }
- [tabVC presentViewController:linkPhone animated:YES completion:^{
-
- }];
- }
- [self loadUserInfo];
- [SVProgressHUD dismiss];
- } failure:^(NSError *error) {
- [SVProgressHUD dismiss];
- [MBProgressHUD showMessage:@"加载失败"];
- }];
- } fail:^(NSError *error) {
-
- }];
- }
- /**
- 加载用户信息
- */
- - (void)loadUserInfo {
-
- if (![AccountTool isLogin]) {
- return;
- }
- [KBHttp post:UserInfo params:nil success:^(id json) {
- self.userInfo = [KBUserInfo yy_modelWithJSON:json];
- [[NSUserDefaults standardUserDefaults] setObject:self.userInfo.phone forKey:UserPhone];
- [[NSUserDefaults standardUserDefaults]synchronize];
- } failure:^(NSError *error) {
-
- }];
- }
- /**
- 微信登录发起授权
- */
- - (void)sendReq{
- SendAuthReq *req = [[SendAuthReq alloc] init];
- req.scope = @"snsapi_userinfo";
- req.state = @"App";
- [WXApi sendReq:req];
-
- }
- #pragma mark ------------- WXApiManagerDelegate -------------
- - (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
- // 授权成功
- if (response.errCode == 0) {
- // 获取用户信息
- [SVProgressHUD show];
- [self getWeChatTokenThenGetUserInfoWithCode:response.code];
- } else if (response.errCode == -2){
- TYAlertView *alert = [TYAlertView alertViewWithTitle:@"温馨提示" message:@"用户拒绝授权"];
- [alert addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:nil]];
- [alert showInController:self preferredStyle:TYAlertControllerStyleAlert];
- } else if (response.errCode == -2){
- TYAlertView *alert = [TYAlertView alertViewWithTitle:@"温馨提示" message:@"用户取消授权"];
- [alert addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:nil]];
- [alert showInController:self preferredStyle:TYAlertControllerStyleAlert];
- }
- }
- #pragma mark ------ prvate ----
- // 获取微信accesstoken
- - (void)getWeChatTokenThenGetUserInfoWithCode:(NSString *)code{
- 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];
- [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
- // responseDict 中含有 refresh_token,expires_in 超时时间
-
- id responseDict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
- NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseDict];
- // NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
- // [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*60*60]];
- // NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:[accessDict[@"expires_in"] intValue]];
- NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
- NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
- // NSString *refreshToken = [accessDict objectForKey:WX_Refresh_TOKEN];
-
-
- [self getWeChatUserInfoWithToken:accessToken andOpenID:openID];
-
- } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
- [SVProgressHUD showInfoWithStatus:@"请求失败"];
- }];
- }
- // 获取微信用户信息
- - (void)getWeChatUserInfoWithToken:(NSString *)token andOpenID:(NSString *)openid{
- // 通过access_token和openid获取用户信息
- NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openid];
- [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
- id responseDict =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
- [self wxLoginRequestWithResponseObject:responseDict];
- } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
- [SVProgressHUD showInfoWithStatus:@"请求失败"];
- }];
- }
- - (void)wxLoginRequestWithResponseObject:(id)responseObject {
- if (responseObject[@"openid"] && responseObject[@"unionid"] && responseObject[@"nickname"] && responseObject[@"headimgurl"]) {
-
- }else {
-
- [SVProgressHUD dismiss];
- [MBProgressHUD showMessage:@"读取微信信息失败,请重试"];
- return;
- }
- NSDictionary *para = @{@"openid":responseObject[@"openid"],
- @"unionid":responseObject[@"unionid"],
- @"nickname":responseObject[@"nickname"],
- @"headimgurl":responseObject[@"headimgurl"]
- };
- NSString *url = [NSString stringWithFormat:@"%@/api/v2/users/weChatLogin",BaseURL];
- [KBHttp post:url params:para success:^(id json) {
-
-
-
- if ([json[@"is_binded_mobile"] boolValue]) {
- //已绑定手机号
- AccountModel *model = [AccountModel yy_modelWithJSON:json];
- [AccountTool saveAccount:model];
- NSString *sex = [NSString stringWithFormat:@"%@",json[@"sex"]];
- [[NSUserDefaults standardUserDefaults] setObject:sex forKey:UserSexKey];
- [[NSUserDefaults standardUserDefaults] synchronize];
- [self dismissViewControllerAnimated:YES completion:nil];
- }else {
- //未绑定
- KBLinkPhoneController *linkPhone = [[KBLinkPhoneController alloc] init];
- [self dismissViewControllerAnimated:NO completion:nil];
- UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
- linkPhone.wx_union_id = responseObject[@"unionid"];
- [tabVC presentViewController:linkPhone animated:YES completion:^{
-
- }];
- }
-
- [SVProgressHUD dismiss];
- } failure:^(NSError *error) {
- [SVProgressHUD dismiss];
- [MBProgressHUD showMessage:@"请求失败"];
- }];
- }
- #pragma mark ----- layzer -----
- - (AFHTTPSessionManager *)manager{
- if (!_manager) {
- _manager = [AFHTTPSessionManager manager];
- _manager.requestSerializer.timeoutInterval = 15;
- _manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 解析为data
- _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
- _manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
- }
- return _manager;
- }
- @end
|