-
-
Save nuno/39b883b2543095d67ab0f92f3e70ccbb 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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