豪哥学ios开发之登录界面
首先在ViewController.h文件中:
#import <UIKit/UIKit.h>
#import "SRWebSocket.h"
//继承SRWebSocket.h,作为登录服务器
@interface ViewController : UIViewController<UITextFieldDelegate,SRWebSocketDelegate>
//- (IBAction)SaveLogin:(id)sender;
//与SB联系账号输入,密码输入与登录按钮,并且设置两个label写上提示账号和密码输入
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *password;
- (IBAction)loginbuttonClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
//@property (weak, nonatomic) IBOutlet UIButton *SaveLogin;
@property (weak, nonatomic) IBOutlet UILabel *lbuser;
@property (weak, nonatomic) IBOutlet UILabel *lbpassword;
@end
然后来到.m文件中:
#import "ViewController.h"
#import "ASIHTTPRequest.h"
#import "MD5.h"
#import "SVProgressHUD.h"
#import "Reachability.h"
#import "UIColor+Extensions.h"
#import "comm.h"
//引用ASIHTTPRequest.h发送请求,MD5将账号密码转译,Reachability.h检查网络链接状态,SVProgressHUD.h后期开发就不用了,UIColor+Extensions.h颜色扩展,comm.h定义聊天服务器,登录服务器地址方便调用
@interface ViewController ()
{
UIImageView *slashimage;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGSize viewSize = [[UIScreen mainScreen] bounds].size;
//设置登录界面背景图片;
UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg.png"]];
//采用自身视图尺寸作为背景大小;
[image setFrame:self.view.frame];
[self.view addSubview:image];
//把背景图放在最底层,不会被释放;
[self.view sendSubviewToBack:image];
//调用键盘的三种状态,对应三种状态需要采用的方法;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
//设置代理;
self.userName.delegate = self;
self.password.delegate = self;
//隐藏导航栏;
[self.navigationController.navigationBar setHidden:YES];
//实现轻量本地化,把账号密码对应相关key存在NSUserDefaults;
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString* strUid = [pref stringForKey:@"uid"];
NSString* strPwd = [pref stringForKey:@"pwd"];
//取出输入框中的对象,赋给变量;
self.userName.text = strUid;
self.password.text = strPwd;
//利用美术组提供的颜色给字体提供新的颜色;
self.userName.textColor = [UIColor colorWithHexString:@"767676"];
self.password.textColor = [UIColor colorWithHexString:@"767676"];
//判断输入框中的对象不为空时,登录按钮才可用
if ([self.userName.text isEqualToString:@""] || [self.password.text isEqualToString:@""])
{
[self.loginButton setEnabled:FALSE];
self.loginButton.titleLabel.textColor = [UIColor grayColor];
}
else
{
[self.loginButton setEnabled:TRUE];
self.loginButton.titleLabel.textColor = [UIColor whiteColor];
}
self.lbuser.backgroundColor = [UIColor colorWithHexString:@"b5b5b5"];
self.lbpassword.backgroundColor = [UIColor colorWithHexString:@"b5b5b5"];
self.loginButton.layer.borderWidth = 1.0f;//定义登录按钮边框
self.loginButton.layer.borderColor = [[UIColor whiteColor] CGColor];
self.loginButton.layer.cornerRadius = 4.0;
self.loginButton.titleLabel.textColor = [UIColor whiteColor];
self.loginButton.backgroundColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:0.15];
//[self performSegueWithIdentifier:@"gotoHome" sender:self.loginButton];
//登录背景设置;
slashimage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Default-568h@2x.png"]];
[slashimage setFrame:self.view.frame];
[self.view addSubview:slashimage];
//登录动画方法;
[self performSelector:@selector(hideSlashImage) withObject:nil afterDelay:1.0];
}
- (void)hideSlashImage
{
[UIView animateWithDuration:0.8 animations:^{
slashimage.alpha = 0.0;
} completion:^(BOOL finished) {
[slashimage removeFromSuperview];
}];
}
- (void) viewWillAppear:(BOOL)animated
{
CGSize viewSize = [[UIScreen mainScreen] bounds].size;
//在视图即将出现时,需要
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString* strUid = [pref stringForKey:@"uid"];
NSString* strPwd = [pref stringForKey:@"pwd"];
self.userName.text = strUid;
self.password.text = strPwd;
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationDidBecomeActiveNotification:)
name:UIApplicationDidBecomeActiveNotification
object:[UIApplication sharedApplication]];
}
- (void) viewWillDisappear:(BOOL)animated
{
}
- (void)applicationDidBecomeActiveNotification:(NSNotification *)notification {
// Do something here
//通过取消第一响应者来隐藏键盘位置
[self.userName resignFirstResponder];
[self.password resignFirstResponder];
}
- (void)viewDidAppear:(BOOL)animated
{
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)loginbuttonClick:(id)sender
{
//向管理平台登录,获取token,并且用将账号密码转为md5格式;
NSString *strUrl = [NSString stringWithFormat:@"%@/login?tel=%@&pwd=%@",WEB_SERVER_HOST,
self.userName.text,[self.password.text MD5EncodedString]];
NSLog(@"%@",strUrl);
//发送异步请求
NSString *strMd5 = [NSString stringWithMD5EncodedString:@"19"];
NSURL *url = [NSURL URLWithString:strUrl];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(@"login result:%@",responseString);
NSError *error = nil;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSString* msgCode = [dict objectForKey:@"code"];
if ([msgCode isEqualToString:@"200"]) {
NSLog(@"login success!");
NSString* token = [dict objectForKey:@"token"];//登录成功就获取token,并保存在NSUserDefaults
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
[pref setValue:token forKey:@"logintoken"];
[pref setValue:self.userName.text forKey:@"uid"];
[pref setValue:self.password.text forKey:@"pwd"];
[pref setBool:TRUE forKey:@"login"];//将登录状态也保存,
//NSString *msgResult = [[dict objectForKey:@"result"] description];
[pref setValue:responseString forKey:@"loginresult"];//将返回的信息保存,以后要解析
//[SVProgressHUD dismiss];
//取消第一响应者,隐藏键盘
[self.userName resignFirstResponder];
[self.password resignFirstResponder];
//切换试图,进入主界面
[self performSegueWithIdentifier:@"gotoHome" sender:self.loginButton];
}
else {
[SVProgressHUD showErrorWithStatus:@"用户名或密码有误,请重新输入。"];
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
[pref setBool:FALSE forKey:@"login"];
return;
}
NSLog(@"msgCode is %@",msgCode);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"login result:%@",error.description);
//因网络原因登录失败提示弹窗
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请检查您的网络后重试!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}];
[request startAsynchronous];
}
#pragma mark - 键盘处理
#pragma mark 键盘即将显示
- (void)keyBoardWillShow:(NSNotification *)note{
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];//根据键盘的这个key来取键盘消失时候的值;
CGFloat ty = self.view.frame.size.height - rect.size.height;//屏幕高度减去键盘高度的值;
CGFloat shift = ty - self.loginButton.frame.origin.y-self.loginButton.frame.size.height;//设置底边高度;
//将视图坐标向上推;
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, shift);
}];
}
#pragma mark 键盘即将退出
- (void)keyBoardWillHide:(NSNotification *)note{
//视图返回原位,CGAffineTransformIdentity是没有使用transform之前的值;
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
self.view.transform = CGAffineTransformIdentity;
}];
}
- (void)textFieldChanged:(NSNotification *)note{
if ([self.userName.text isEqualToString:@""] || [self.password.text isEqualToString:@""])
{
[self.loginButton setEnabled:FALSE];
self.loginButton.titleLabel.textColor = [UIColor grayColor];
}
else
{
[self.loginButton setEnabled:TRUE];
self.loginButton.titleLabel.textColor = [UIColor whiteColor];
}
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
//默认不跳转,等待登陆结果
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
BOOL blogin = [pref boolForKey:@"login"];
if (blogin) {
return TRUE;
}
return FALSE;
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
}
@end