zoukankan      html  css  js  c++  java
  • [IOS 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个字段的值清空。


    ___________________________________________________
    专注iOS/前端开发,广泛涉猎多种平台和技术,欢迎交流
    可以在微博关注并@沈z伟
  • 相关阅读:
    Mysql Select 语句中实现的判断
    SQL根据一个字符串集合循环保存数据库
    SQL语句 不足位数补0
    SVN常见错误
    svn架构
    关于EXCEL显示数字
    exception from hresult:0x8000401A(excel文档导出)
    WIN7安装注意事项
    解决卸载时残留目标文件夹的问题
    Installshield执行多条批处理的方法
  • 原文地址:https://www.cnblogs.com/rayshen/p/3815424.html
Copyright © 2011-2022 走看看