Search code examples
cookiestitaniumtitanium-mobiletitanium-alloytitanium-modules

how to store data to local device from server with titanium?


I want to make a auto login when users used APP after first time.I tried to keep it in alloy.js and Ti.App.Properties.getString('login_token'),but they didn't work.

in my coffee:

result = JSON.parse this.responseText
console.info result.token  #"dsfdsfds2142fds3r32rf32e3dfefwedf"
Ti.App.Properties.setString "token",result.token
console.info Ti.App.Properties.getString "token"  # it's blank

Solution

  • I couldn't find a built in way to do this so i just created a getter and setter method and put it in alloy.js. Feels very hacky and dirty but it does work.

    //retrieves the value of the token
    // also checks if the token is valid and sets logged_in accordingly
    function getToken(){
        var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'api.txt');
        var content = f.read();
    
        //if we can read this return it, otherwise return a blank value
        if (content){
          return content.text;  
        }
        else {
            return '';
        }
    }
    
    //persists and sets the value of token to the new value
    function setToken(key){
        var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'api.txt');
        f.deleteFile();
        var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'api.txt');
        f.write(key);
        token = key;
    }