简单登录逻辑Demo

结合MD5加密的方式,简单介绍一下登录保存账号密码的逻辑
前言:
1."NSString+Hash.h"是一个MD5加密的分类
2.这里使用了Apache搭建了一个简单的本地服务器来进行演示
3.使用NSURLConnection演示发送登录请求,请求字段匹配(userId.intValue == 1),代表登录成功,此时将真确的账号密码保存至偏好设置
4.首次登录,对密码进行一次MD5加密,将加密后的密码发送至服务器
5.设置一个标识用于判断是否为首次登录,首次登录对密码进行加密
6.iOS7后苹果加入了钥匙串的功能,这里将信息保存至沙盒演示

#import "ViewController.h"
#import "NSString+Hash.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *tf_username;
@property (weak, nonatomic) IBOutlet UITextField *tf_password;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //从沙盒获取用户名和密码
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *username = [defaults objectForKey:@"username"];
    NSString *password = [defaults objectForKey:@"password"];
    
    //给控件赋值
    self.tf_username.text = username;
    self.tf_password.text = password;
    
}
- (IBAction)loginBtnClick:(id)sender {
    
    //获取用户名和密码
    NSString *username = self.tf_username.text;
    NSString *password = self.tf_password.text;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *flag = [defaults objectForKey:@"flag"];
    //如果是第一次
    if (!flag.boolValue) {
        password = [password md5String];
        //更改标识
        [defaults setObject:@YES forKey:@"flag"];
        [defaults synchronize];
    }

    //1. URL
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php"];
    
    //2. 根据URL创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求体的数据
    NSString *string = [NSString stringWithFormat:@"username=%@&password=%@",username,password] ;
    //设置请求体
    request.HTTPBody = [string dataUsingEncoding:NSUTF8StringEncoding];
    //设置请求方法
    request.HTTPMethod = @"POST";
    
    //3.建立连接发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        if (connectionError != nil || data == nil) {
            NSLog(@"请求失败");
        }

        //数据解析/反序列化
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
        NSNumber *userId = [dict objectForKey:@"userId"];
        
        //判断是否登录成功
        if (userId.intValue == 1) {
            //保存用户名
            [defaults setObject:username forKey:@"username"];
            [defaults setObject:password forKey:@"password"];
            
            //同步一下, iOS8以后不需要调用,系统会自动调用
            [defaults synchronize];
            
        }
        
        NSLog(@"%@",dict);
    }];

}

@end

你可能感兴趣的:(简单登录逻辑Demo)