iOS·Swift 数据持久化(一)NSUserDefaults偏好设置

用NSUserDefaults存储配置信息分两种情况:
1.如果是密码用户名等敏感信息,一般不使用NSUserDefaults,而是用Keychain存储用户敏感信息。
2.如果是设置 第一次打开应用引导界面、记住密码,那么,可使用NSUserDefaults。

项目dome已经上传GitHub:***https://github.com/BigTortoise/LearnNSUserDefaults ***

首次登陆,APP引导介绍页

先贴上引导页的代码

//配置scrollView
        scrollView.frame = self.view.bounds
        scrollView.contentSize = CGSizeMake(4*self.view.frame.width, 0)
        scrollView.pagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self
        self.view.addSubview(scrollView)
        for var i=0;i<4;i++ {
            let image = UIImage(named: "\(i+1)")
            let imageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
            imageView.image = image
            var frame = imageView.frame
            frame.origin.x = CGFloat(i)*frame.size.width
            imageView.frame = frame
            scrollView.addSubview(imageView)
            self.view.addSubview(pageControl)
        }
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / self.view.frame.size.width)    //获取当前页数
        pageControl.currentPage = index
        //在这里添加按钮的渐入效果,当页面滑到第4页时出现
        if(index == 3)
        {
            self.btn.frame = CGRectMake(3*self.view.frame.width, self.view.frame.height, self.view.frame.width, 50)
            self.btn.setTitle("开启Swift之旅", forState: UIControlState.Normal)
            self.btn.titleLabel?.font = UIFont.systemFontOfSize(20)
            self.btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
            self.btn.backgroundColor = UIColor.orangeColor()
            self.btn.alpha = 0
            self.btn.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            UIView.animateWithDuration(1.5, delay: 0.5, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                self.btn.frame = CGRectMake(3*self.view.frame.width, self.view.frame.height-100, self.view.frame.width, 50)
                self.btn.alpha = 1
                //注意把按钮添加到scrollView上,不要添加到imageView上,会无法点击
                self.scrollView.addSubview(self.btn)
                }, completion: nil)
        }
    }
//配置pageControl
        pageControl.center = CGPointMake(self.view.frame.width/2, self.view.frame.height-30)
        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
        pageControl.pageIndicatorTintColor = UIColor.whiteColor()
        pageControl.numberOfPages = 4
        pageControl.addTarget(self, action: "scrollViewDidEndDecelerating", forControlEvents: UIControlEvents.ValueChanged)
 //按钮点击事件
    func buttonClick(button:UIButton)
    {
        //界面的跳转
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let secondVC = sb.instantiateViewControllerWithIdentifier("second")
        self.presentViewController(secondVC, animated: true, completion: nil)
    }

终于轮到NSUserDefaults出场了!!!

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //判断App是否第一次启动
        if(!NSUserDefaults.standardUserDefaults().boolForKey("firstLaunch"))
        {
            self.window?.rootViewController = ViewController()
            self.window?.makeKeyAndVisible()
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstLaunch")
        }
        else
        {
            let sb = UIStoryboard(name: "Main", bundle: nil)
            let secondVC = sb.instantiateViewControllerWithIdentifier("second")
            self.window?.rootViewController = secondVC
            self.window?.makeKeyAndVisible()
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstLaunch")
        }
        return true

到此已经完成引导页的编码,来看一下运行效果吧。


iOS·Swift 数据持久化(一)NSUserDefaults偏好设置_第1张图片
导航页.gif

记住用户信息

来看代码

     @IBOutlet weak var userNmae: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var rembSwich: UISwitch!
 @IBAction func login(sender: UIButton) {

        //读取上次配置
        self.userNmae.text =
            NSUserDefaults.standardUserDefaults().valueForKey("UserName") as! String!
        self.password.text = NSUserDefaults.standardUserDefaults().valueForKey("password")as! String!
        self.rembSwich.on = NSUserDefaults.standardUserDefaults().boolForKey("RmbPwdKey") as Bool!
        if (self.rembSwich.on){
            self.password.text = NSUserDefaults.standardUserDefaults().valueForKey("PwdKey") as! String!
        }
        
        NSUserDefaults.standardUserDefaults().setObject(self.userNmae.text, forKey: "UserName")
        NSUserDefaults.standardUserDefaults().setObject(self.password.text, forKey: "password")
        NSUserDefaults.standardUserDefaults().setBool(self.rembSwich.on, forKey: "RmbPwdKey")
        //设置同步
        NSUserDefaults.standardUserDefaults().synchronize()
        
       // 读取上次配置
        self.userNmae.text =
            NSUserDefaults.standardUserDefaults().valueForKey("UserName") as! String!
        self.password.text = NSUserDefaults.standardUserDefaults().valueForKey("password")as! String!
        self.rembSwich.on = NSUserDefaults.standardUserDefaults().boolForKey("RmbPwdKey") as Bool!
        if (self.rembSwich.on){
            self.password.text = NSUserDefaults.standardUserDefaults().valueForKey("PwdKey") as! String!
        }
        
    }

运行结果


iOS·Swift 数据持久化(一)NSUserDefaults偏好设置_第2张图片
记住用户信息.gif

你可能感兴趣的:(iOS·Swift 数据持久化(一)NSUserDefaults偏好设置)