Skip to content

Instantly share code, notes, and snippets.

Created July 29, 2015 17:43
Show Gist options
  • 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()) {
file = null;
} else {
var retries = 5;
getRemoteFile(url, retries, function (responseData){
file = null;
function checkIfPathExistOrCreateIt(directory) {
var fileSystem = Ti.Filesystem.applicationDataDirectory;
var folder = Ti.Filesystem.getFile(fileSystem, directory);
if (!folder.exists()) {
function getRemoteFile(url, retries, success) {
var http = Ti.Network.createHTTPClient();
http.onload = function() {
if (http.status == 200) {
} else {
if (retries > 0) {
getRemoteFile(url, success, retries - 1);
} else {
console.log('making too much retries, stopping for url ' + url);
};'GET', url);
var cachedImage = require("cache").image;
var url = "";
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