我需要为Android设备缓存我的HttpClient响应。官方文件中给出的例子适用于Iphone& iPad兼容。
答案 0 :(得分:0)
好的,这是实现这一目标的一种方法:
在您的httpRequests成功处理程序中,为您的回复附加“时间戳”:
// 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);
在你的按钮eventListener中,我们将检查已经过的时间
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
}
});
此函数以小时计算时差
// 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;
}
的注意
这不是一个完整的示例,您必须根据需要优化和更改代码。