How to save data in mobile cache?


#1

how to save and read data from mobile cache?
in my ionic application i must get a lot of data from http address (my website) .
i want to save data in json file on mobile devise cache for first time.
and then just read data from cache and if it(data on website) change i read new data from http address and update my json file.
i want to be my application more faster.
is there any way to do it? any sample?


#2

Sounds like you could use localStorage.


#3

This is quite a big question that covers a lot of different topics.

Storing data locally - http://learn.ionicframework.com/formulas/localstorage/ - local Storage is a straight forward, fast way to cache data. It’s not ‘clever’ but it works really nicely. You’ll need to get that working in your app first.

When you’ve got $localStorage working you can do a few things.

First, when the user runs the app for the first time, check for a $localStorage value like;

var init = $localStorage.get('init');

if (init.setup === undefined) {

}

That will return undefined. That’s good. Then change the code to set an init value if it’s undefined.

var init = $localStorage.get('init');

if (init.setup === undefined) {

    $localStorage.set('init',{'setup':'done'});

}

What that will do is check for the ‘setup’ flag, and if it’s false then it’ll run the setup code. The next time it runs the flag will be found so the setup code won’t run again.

Now that you’ve got an initialisation function you can fetch the data and put it in the cache;

var init = $localStorage.get('init');

if (init.setup === undefined) {

    $localStorage.set('init',{'setup':'done'});

    $http.get(url)
        .success(function(data) {
            $localStorage.set('data',data);
        })
        .error(function() {
            console.log("Didn't work");
        });

} else {

    var data = $localStorage.get('data');

}

Now the data will be fetched the first time the app loads and then fetched from localStorage on subsequent loads.

A couple of things to note;

  1. $http.get() returns a promise - your code will continue to run while it’s fetching the data in the background. That means you might get errors if you don’t handle the promise correctly. Read this: http://learn.ionicframework.com/formulas/data-the-right-way/

  2. Putting all the data in one localStorage object is probably wrong for your app. You almost certainly want to break up the object you get from your site and store it in several logical objects.


#4

thanks for your good information. :grinning:
i’ll try it.