我们能否缓存动态创建的列表或 View ,直到在后台调用 web 服务。我想实现像 FaceBook 应用程序那样的功能。我知道它在 Android Core 中是可行的,但想在 Titanium(Android 和 IOS)中尝试。
我会进一步解释, 假设我有一个有列表的应用程序。现在,当我第一次打开时,它显然会访问 web 服务并创建一个动态列表。
现在我关闭应用程序并再次打开应用程序。在网络服务提供任何数据之前,旧列表应该是可见的。
最佳答案
是的,Titanium 可以做到这一点。如果它只是一个数组/列表/变量,您应该使用像 Ti.App.myList
这样的全局变量。如果您需要存储更复杂的数据,如图像或数据库,您应该使用内置文件系统。关于 Appcelerator website 的文档非常好.
您的程序如下:
- 首次加载您的数据
- 以您喜欢的方式存储您的数据(全局变量、文件系统)
- 在未来的应用程序启动期间,读取您的本地列表/数据并显示它,直到您的同步成功。
您应该考虑实现一些变量来检查是否需要任何更新以尽量减少网络使用(如果用户的互联网连接速度较慢,它可以节省能源并提供更好的用户体验)。
if (response.state == "SUCCESS") {
Ti.API.info("Themes successfully checked");
Ti.API.info("RESPONSE TEST: " + response.value);
//Create a map of the layout names(as keys) and the corresponding url (as value).
var newImageMap = {};
for (var key in response.value) {
var url = response.value[key];
var filename = key + ".jpg"; //EDIT your type of the image
newImageMap[filename] = url;
}
if (Ti.App.ImageMap.length > 0) {
//Check for removed layouts
for (var image in Ti.App.imageMap) {
if (image in newImageMap) {
Ti.API.info("The image " + image + " is already in the local map");
//Do nothing
} else {
//Delete the removed layout
Ti.API.info("The image " + image + " is deleted from the local map");
delete Ti.App.imageMap[image];
}
}
//Check for new images
for (var image in newImageMap) {
if (image in Ti.App.imageMap) {
Ti.API.info("The image " + image + " is already in the local map");
//Do nothing
} else {
Ti.API.info("The image " + image + " is put into the local map");
//Put new image in local map
Ti.App.imageMap[image] = newImageMap[image];
}
}
} else {
Ti.App.imageMap = newImageMap;
}
//Check wether the file already exists
for (var key in response.value) {
var url = response.value[key];
var filename = key + ".png"; //EDIT YOUR FILE TYPE
Ti.API.info("URL: " + url);
Ti.API.info("FILENAME: " + filename);
imagesOrder[imagesOrder.length] = filename.match(/\d+/)[0]; //THIS SAVES THE FIRST NUMBER IN YOUR FILENAME AS ID
//Case1: download a new image
var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "/media/" + filename);
if (file.exists()) {
// Do nothing
Titanium.API.info("File " + filename + " exists");
} else {
// Create the HTTP client to download the asset.
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
if (xhr.status == 200) {
// On successful load, take that image file we tried to grab before and
// save the remote image data to it.
Titanium.API.info("Successfully loaded");
file.write(xhr.responseData);
Titanium.API.info(file);
Titanium.API.info(file.getName());
};
};
// Issuing a GET request to the remote URL
xhr.open('GET', url);
// Finally, sending the request out.
xhr.send();
}
}
除了应该放在 API 调用的成功方法中的这段代码外,您还需要一个全局变量 Ti.App.imageMap
来存储键映射和相应的 url。我想您必须稍微更改代码以满足您的需求和您的项目,但它应该为您提供一个良好的起点。
关于web-services - Android/iOS 中的钛合金缓存?或保留旧 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26753676/