Skip to content

Instantly share code, notes, and snippets.

@decklord
Created July 29, 2015 17:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save decklord/a2284b915dcbf0f6307f to your computer and use it in GitHub Desktop.
Save decklord/a2284b915dcbf0f6307f to your computer and use it in GitHub Desktop.
This file is a cache module for Appcelerator Platform, now it works just with images but can be extended to support other stuff. Currently supports n number of retries and gets the image path on a callback, so you don't need to fake a dummy imageView if you want to precache some image.
exports.image = function(url, callback, directory) {
if (directory === undefined) {
var directory = 'cachedImages';
}
var filename = Ti.Utils.md5HexDigest(url);
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, directory, filename);
if (file.exists()) {
callback(file.nativePath);
file = null;
} else {
checkIfPathExistOrCreateIt(directory);
var retries = 5;
getRemoteFile(url, retries, function (responseData){
file.write(responseData);
callback(file.nativePath);
file = null;
});
}
};
function checkIfPathExistOrCreateIt(directory) {
var fileSystem = Ti.Filesystem.applicationDataDirectory;
var folder = Ti.Filesystem.getFile(fileSystem, directory);
if (!folder.exists()) {
folder.createDirectory();
}
};
function getRemoteFile(url, retries, success) {
var http = Ti.Network.createHTTPClient();
http.onload = function() {
if (http.status == 200) {
success(http.responseData);
} else {
if (retries > 0) {
getRemoteFile(url, success, retries - 1);
} else {
console.log('making too much retries, stopping for url ' + url);
}
}
};
http.open('GET', url);
http.send();
};
/*
Usage:
var cachedImage = require("cache").image;
var url = "http://placekitten.com/200/300";
cachedImage(url, function (imgPath){
$.someImageView.image = imgPath;
});
If you want to pre-cache something you can use it like this:
cachedImage(url, function (imgPath){});
If you want to use another folder as the cache folder, to avoid collision, you can specify it. By default it will use "cachedImages" folder.
cachedImage(url, function (imgPath){}, 'SomeOtherCacheFolder');
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment