swift -> local storage learning

** Get the document path

        let pathArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);

        let path = pathArray[0];

        print("path: \(path)");

** plist storage

         //Write 

              You can also write setValue(xxxxx,xxx);

        let dict = NSMutableDictionary();

        dict.setObject("testname", forKey: "name");

        dict.setObject("testpass", forKey: "pwd");

        dict.writeToFile("\(path)/ss.plist", atomically: true); 

        

        //read 

        let readDict = NSDictionary.init(contentsOfFile: "\(path)/ss.plist");

        //let ff = readDict?.objectForKey("pwd");

        let ff = readDict?.valueForKeyPath("pwd") as! String;

        print("read result: \(ff)");

 

**  Preference  NSUserDefaults storage, mainly used to store personal information, such as username, password, etc.

        let userInfo = NSUserDefaults.standardUserDefaults();

        userInfo.setObject("123456", forKey: "pwd");

        userInfo.setBool(true, forKey: "logined");

        userInfo.synchronize();

        

        let getUser = NSUserDefaults.standardUserDefaults();

        let v = getUser.objectForKey("pwd") as! String;

        lb.text = v;

 

        print("\(v)");

 The new version of swift (for example, the judgment value is regardless of today's date, if not, it is updated to today's date)

        let nowDate = NSDate()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateString = formatter.string(from: nowDate as Date)

        let getUser = UserDefaults.standard

        var local_upload_tongji = "";
        / / Determine whether the corresponding key exists
        if(getUser.object(forKey: "upload_tongji_date") != nil){
            local_upload_tongji = getUser.object(forKey: "upload_tongji_date") as! String;
        }
 
        if(dateString != local_upload_tongji){
            print("not set local");
            getUser.set(dateString, forKey: "upload_tongji_date");
            //remember to save
            getUser.synchronize();
        }else{
            print(" has set local:")
        }

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326908495&siteId=291194637