Newer
Older
XinYang_IOS / LoginViewController.m
@zhangfeng zhangfeng on 7 Dec 15 KB 1.8.0
//
//  LoginViewController.m
//  YHScrollView_Test
//
//  Created by Jim on 2021/9/4.
//

#import "LoginViewController.h"
#import "AppDelegate.h"


@interface LoginViewController ()<UITextFieldDelegate>{
    CGFloat   subHeight;
}

@property (nonatomic,strong)UITextField * accountTextField;
@property (nonatomic,strong)UITextField * passwordTextField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(keyboardWillHide:)
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    
    UIImageView *topbackImageV = [[UIImageView alloc] init];
    topbackImageV.image = [UIImage imageNamed:@"top_back_image"];
    [self.view addSubview:topbackImageV];
    [topbackImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.centerX.mas_equalTo(0);
        make.width.mas_equalTo(KScreenWidth);
        make.height.mas_equalTo(Auto_Width(300));
    }];
    
    UIImageView *titleImageV = [[UIImageView alloc] init];
    titleImageV.image = [UIImage imageNamed:@"title_image"];
    [self.view addSubview:titleImageV];
    [titleImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topbackImageV.mas_bottom).offset(2);
        make.centerX.equalTo(topbackImageV);
        make.width.mas_equalTo(Auto_Width(206));
        make.height.mas_equalTo(Auto_Width(32));
    }];
    
    
    UIView *lineViewOne = [UIView new];
    lineViewOne.backgroundColor = UIColorFromRGB(0xcccccc);
    [self.view addSubview:lineViewOne];
    [lineViewOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleImageV);
        make.width.mas_equalTo(Auto_Width(270));
        make.top.equalTo(titleImageV.mas_bottom).offset(IS_iPhoneX ? 110 : 55);
        make.height.mas_equalTo(1);
    }];
    
    
    UIImageView *userIcon = [UIImageView new];
    userIcon.image = [UIImage imageNamed:@"username_icon"];
    [self.view addSubview:userIcon];
    [userIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineViewOne.mas_left).offset(0);
        make.bottom.equalTo(lineViewOne.mas_bottom).offset(-15);
        make.size.mas_equalTo(CGSizeMake(15, 15.5));
    }];
    
    _accountTextField = [[UITextField alloc]init];
    _accountTextField.textColor = UIColorFromRGB(0x333333);
    _accountTextField.tintColor = UIColorFromRGB(0x333333);
    _accountTextField.returnKeyType=UIReturnKeyNext;
    _accountTextField.delegate=self;
    _accountTextField.font=[UIFont systemFontOfSize:13];
    _accountTextField.backgroundColor=[UIColor clearColor];
    _accountTextField.keyboardType = UIKeyboardTypeASCIICapable;
    _accountTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xcccccc),NSFontAttributeName:[UIFont systemFontOfSize:13]}];
    
    [_accountTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_accountTextField];

    [_accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(userIcon.mas_right).offset(5.0);
        make.centerY.equalTo(userIcon.mas_centerY).offset(0);
        make.right.equalTo(lineViewOne.mas_right).offset(-10.0);;
        make.height.mas_equalTo(30.0);
    }];
    
    
    UIView *lineViewTwo = [UIView new];
    lineViewTwo.backgroundColor = UIColorFromRGB(0xcccccc);
    [self.view addSubview:lineViewTwo];
    [lineViewTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(lineViewOne);
        make.width.mas_equalTo(Auto_Width(270));
        make.top.equalTo(lineViewOne.mas_bottom).offset(70);
        make.height.mas_equalTo(1);
    }];
    
    
    UIImageView *passIcon = [UIImageView new];
    passIcon.image = [UIImage imageNamed:@"password_icon"];
    [self.view addSubview:passIcon];
    [passIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineViewTwo.mas_left).offset(0);
        make.bottom.equalTo(lineViewTwo.mas_bottom).offset(-15);
        make.size.mas_equalTo(CGSizeMake(15, 15.5));
    }];
    
    _passwordTextField = [[UITextField alloc]init];
    _passwordTextField.textColor = UIColorFromRGB(0x333333);
    _passwordTextField.tintColor = UIColorFromRGB(0x333333);
    _passwordTextField.returnKeyType=UIReturnKeyNext;
    _passwordTextField.delegate=self;
    _passwordTextField.font=[UIFont systemFontOfSize:13];
    _passwordTextField.backgroundColor=[UIColor clearColor];
    _passwordTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _passwordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    [_passwordTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    _passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xcccccc),NSFontAttributeName:[UIFont systemFontOfSize:13]}];
    
    [_passwordTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_passwordTextField];

    [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(passIcon.mas_right).offset(5.0);
        make.centerY.equalTo(passIcon.mas_centerY).offset(0);
        make.right.equalTo(lineViewTwo.mas_right).offset(-10.0);;
        make.height.mas_equalTo(30.0);
    }];
    
    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectBtn.tag = 339;
    [selectBtn setBackgroundImage:[UIImage imageNamed:@"sure_select_icon"] forState:UIControlStateSelected];
    [selectBtn setBackgroundImage:[UIImage imageNamed:@"sure_normal_icon"] forState:UIControlStateNormal];
    [selectBtn addTarget:self action:@selector(rememberPassword:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineViewTwo.mas_left).offset(0);
        make.top.equalTo(lineViewTwo.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(15, 15));
    }];
    
    UILabel *tipLabel = [UILabel new];
    tipLabel.textColor = UIColorFromRGB(0x333333);
    tipLabel.font = [UIFont systemFontOfSize:13];
    tipLabel.text = @"记住密码";
    [self.view addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(selectBtn);
        make.left.equalTo(selectBtn.mas_right).offset(5);
        make.height.mas_equalTo(15);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setBackgroundColor:UIColorFromRGB(0x1679FF)];
    [loginBtn setTitle:@"登  录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [loginBtn addTarget:self action:@selector(clickLoginHandleEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineViewTwo.mas_left).offset(0);
        make.top.equalTo(selectBtn.mas_bottom).offset(40);
        make.right.equalTo(lineViewTwo.mas_right).offset(0);
        make.height.mas_equalTo(40);
    }];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_password"]]) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_password"]];
        selectBtn.selected = YES;
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_userID"]]) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_userID"]];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

//记录键盘是否移动过;
static bool isMove;
- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:0.2 animations:^{
            //view的最大y值
            CGFloat maxY = CGRectGetMaxY(self.view.frame);
            //比较view和键盘的y判断是否需要移动
            isMove = maxY > height ? YES:NO;
                if (isMove) {
                    //移动的距离
                    self->subHeight = maxY-2*height;
                    //移动,注意不能直接改frame;
                    self.view.transform = CGAffineTransformMakeTranslation(0, self.view.transform.ty-self->subHeight);
                }
        }];
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.1 animations:^{
           //如果移动了,移动回来.
           if (isMove) {
               self.view.transform =CGAffineTransformMakeTranslation(0,self.view.transform.ty+self->subHeight);

           }
       }];
}

#pragma mark - 控制字符输入
- (void)textFieldChange:(UITextField *)textField{
    NSString *toBeString = textField.text;
    
    if (textField==self.passwordTextField)
    {
        if (toBeString.length>64) {
            textField.text = [toBeString substringToIndex:64];
        }
    }
    
    if (textField==self.accountTextField)
    {
        if (toBeString.length>64) {
            textField.text = [toBeString substringToIndex:64];
        }
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
        return NO;
    }
    
    if (textField==self.passwordTextField)
    {
       
        if ([Untis Fish_haveEmoji:string]) {//表情不能输入
            return NO;
        }
        if(string.length>1)
        {
            if ([Untis Fish_haveChinese:string]) {//有中文不能输入
                return NO;
            }
        }

    }else if (textField==self.accountTextField){
        return YES;
    }
    
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField==self.accountTextField) {
        
       [self.passwordTextField becomeFirstResponder];
    }
    if (textField==self.passwordTextField) {
        [self.view endEditing:YES];
    }
   
    return YES;
}

#pragma mark --- 记住密码
-(void)rememberPassword:(UIButton *)sender{
    
    if (!self.accountTextField.text.length) {
        [self.view makeToast:@"您还没有输入用户名哦!"];
        return;
    }
   
    if (!self.passwordTextField.text.length) {
        [self.view makeToast:@"您还没有输入密码哦!"];
        return;
    }
   
    sender.selected = !sender.selected;
    if (sender.selected) {
        [[NSUserDefaults standardUserDefaults] setObject:self.accountTextField.text forKey:[NSString stringWithFormat:@"kuid_userID"]];
        // 记住密码
        [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:[NSString stringWithFormat:@"kuid_password"]];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:[NSString stringWithFormat:@"kuid_userID"]];
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:[NSString stringWithFormat:@"kuid_password"]];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark--- 登录
-(void)clickLoginHandleEvent{
    
    if (!self.accountTextField.text.length) {
        [self.view makeToast:@"您还没有输入账号哦!"];
        return;
    }
    
    if (!self.passwordTextField.text.length) {
        [self.view makeToast:@"您还没有输入密码哦!"];
        return;
    }
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    request.timeoutInterval = 15;
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [request setURL:[NSURL URLWithString:@"http://36.133.215.233:9500/api/logininfo/login"]];
    
    NSDictionary *requestDic = @{@"userNo":self.accountTextField.text,
                                 @"password":self.passwordTextField.text
    };
   
    [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:requestDic options:NSJSONWritingPrettyPrinted error:nil]];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    [YJProgressHUD showProgress:@"加载中..." inView:self.view];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [YJProgressHUD showSuccess:@"加载成功" inview:self.view];
            });
            NSString *results = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
            NSDictionary *dataInfo=[results jsonValue];
            NSLog(@"info == %@",dataInfo);
            NSDictionary *dict = dataInfo[@"data"];
            NSString *token = dict[@"token"];
            NSString *userName = dict[@"userName"];
            [[NSUserDefaults standardUserDefaults] setObject:userName forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:[NSString stringWithFormat:@"token_%@",kUserName]];
            /** 配置OpenVpn*/
            
            /** 进入主页*/
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
            });
            NSLog(@"error == %@",error);
        }
    }];
    [dataTask resume];
}

-(void)goToMainView{
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"login"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [AppDelegate startMainViewController];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end