I need to cache my HttpClient response for android device. The Example given in their official document applies for Iphone & IPad.
Asked
Active
Viewed 278 times
0
-
Please clarify, with caching you mean saving `this.responseText`...? – mwfire Oct 04 '13 at 10:17
-
yes, There is button which requests to server every time. But my response text will be same for the next 24 hrs. – user1795109 Oct 04 '13 at 10:29
1 Answers
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
-
Thanks for your reply, I was trying to avoid that approach, that's why i was searching for the cache – user1795109 Oct 10 '13 at 08:57