首页 > 代码库 > [NSUserDefaults]的使用:登陆后不再显示登录界面。
[NSUserDefaults]的使用:登陆后不再显示登录界面。
之前搜了好多地方都没找到实现“登陆后不再显示登录界面,而默认自动登录”的方法。
待我发现有种存储方式叫NSUserDefaults的时候,立马又感觉新技能get了。
简介:
NSUserDefaults是IOS应用用来存储用户偏好和配置信息的途径,就像是一个数据库,但是它通过键值对(key-value)的方式存储。
比如["Thematrix" forkey:"blogname"]
使用方法:
一共需要3个key,分别是"Didlogin" "username""userpassword"
1.在AppDelegate.m的LaunchOption函数里:判断"Didlogin"字段:Yes->直接首页;No->登录页面。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ // Override point for customization after application launch. UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]; if(![[NSUserDefaults standardUserDefaults] boolForKey:@"Didlogin"]){ NSLog(@"未进行过登录,进行登录"); LoginViewController *LoginViewController =[storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"]; self.window.rootViewController = LoginViewController; } else { NSLog(@"已经进行过登录,直接到首页"); IndexViewController * IndexViewController = [storyboard instantiateViewControllerWithIdentifier:@"IndexViewController"]; self.window.rootViewController = IndexViewController; } return YES;}
2.在LoginViewController.m里:
如果成功登录,就把"Didlogin"设置成Yes,"username"和“userpassword”用来记录账号密码,以便下次自动登录时使用。
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:self.username forKey:@"NSusername"]; [defaults setObject:self.password forKey:@"NSpassword"]; [defaults setBool:YES forKey:@"Didlogin"]; [defaults synchronize];//这句话的意义在于写入硬盘,必须。
3.退出账号后,记得把这3个字段的值清空。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。