0

I need to cache my HttpClient response for android device. The Example given in their official document applies for Iphone & IPad.

user1795109
  • 678
  • 2
  • 6
  • 14

1 Answers1

0

Ok, here is one approach to achieve this:

Within your httpRequests success handler, attach a "timestamp" to your response:

// Assuming you are working with JSON data
var response = JSON.parse(this.responseText);
response.timestamp = new Date();

// For the purpose of this example, we persist our response to properties
Ti.App.Properties.setObject('cachedResponse', response);

In your button eventListener we will check for the time that has passed

button.addEventListener('click', function() {        
    var cachedResponse = Ti.App.Properties.getObject('cachedResponse', { timestamp: false });
    if(cachedResponse.timestamp) {
        if(getHoursDiff(cachedResponse.timestamp, new Date()) > 24) {
            // Last request older than 24 hours, reload data
        } else {
            // Last request was within 24 hours, use cached data
        }
    } else {
       // No data has been saved yet, load Data
    } 
});

This function calculates the time difference in hours

// http://blogs.digitss.com/javascript/calculate-datetime-difference-simple-javascript-code-snippet/
function getHoursDiff(earlierDate, laterDate) {
       var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
       var hours = Math.floor(nTotalDiff/1000/60/60);
       return hours;
}


Note
This is not a complete example, you have to optimize and change the code to your needs.

mwfire
  • 1,657
  • 13
  • 21