HRAccountTool.h:
#import <Foundation/Foundation.h> @interface HRAccountTool : NSObject /** * 存储账号信息 * @param account 需要存储的账号信息:第一个值为用户名;第二个值为密码 */ + (void)saveAccount:(NSArray *)account; /** * 返回存储的账号信息 * @return NSArray */ + (NSArray *)getAccount; /** * 返回存储的登陆用户名 * @return NSString */ + (NSString *)getUserName; /** * 返回存储的登陆用户密码 * @return NSString */ + (NSString *)getPassword; @end
HRAccountTool.m:
<pre name="code" class="objc">#import "HRAccountTool.h" @implementation HRAccountTool + (void)saveAccount:(NSArray *)account{ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; //保存数据 用户信息;用户名;用户密码 [userDefaults setObject:account forKey:@"account" ]; [userDefaults setObject:[account objectAtIndex:0] forKey:@"userName" ]; [userDefaults setObject:[account objectAtIndex:1] forKey:@"passWord" ]; }; + (NSArray *)getAccount{ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSArray *array = [userDefaults objectForKey:@"account"]; return array; }; + (NSString *)getUserName{ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *userName = [userDefaults objectForKey:@"userName"]; return userName; }; + (NSString *)getPassword{ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *passWord = [userDefaults objectForKey:@"passWord"]; return passWord; } @end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; // 先判断有无存储账号信息 if ([HRAccountTool getUserName] == nil) { // 之前没有登录成功 self.window.rootViewController = [[HRLoginViewController alloc] init]; } else {// 之前登录成功 // self.window.rootViewController = [[IWOAuthViewController alloc] init]; } [self.window makeKeyAndVisible]; return YES; }
- (void) loginCheck{ // 1.创建请求管理对象 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 说明服务器返回的JSON数据 mgr.responseSerializer = [AFJSONResponseSerializer serializer]; // 2.封装请求参数 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@"userName"] = userNameTF.text; params[@"passWord"] = passWordTF.text; // 3.发送请求 [mgr GET:@"http://localhost:8080/login/check.do" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) { if ([[responseObject objectForKey:@"success"] boolValue] == true) { self.view.window.rootViewController = [[ZYTabBarViewController alloc]init]; NSArray *array = [NSArray arrayWithObjects:userNameTF.text, passWordTF.text, nil ]; [HRAccountTool saveAccount:array]; }else{ self.view.window.rootViewController = [[ZYloginViewController alloc]init]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { HRLog(@"请求失败:%@", error); }]; }
原文地址:http://blog.csdn.net/zhongyuan_1990/article/details/44964377