Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Appcelerator Titanium ImageView /w cache and cacheage. Supports retina display.
cachedImageView = function(basedir, uri, obj, attr, cacheage) {
Appcelerator Titanium ImageView /w cache
This function attempts to cache a remote image and then returns it again
when it's requested.
The file is stored in a directory "basedir," this is to try and help
you keep files unique. It's not special or magical, but not dirty either.
basedir + filename are used to determine if the file exists locally,
if not it's then fetched from uri, stores and sets the "image" property
of obj.
var imgv = Ti.UI.createImageView({
width: 90,
height: 90,
image: 'default.png'
cachedImageView('bucket_name', '', imgv, "image", 1000); // 1 second, cache expiry.
cachedImageView('bucket_name', '', imgv, "hires", 1000);
var filename = uri.split('/');
filename = filename[filename.length - 1];
var storedTime = Ti.App.Properties.getDouble("CACHE_TIME_"+filename, -1);
var now = new Date().getTime();
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, basedir, filename);
if (f.exists() && ((now - storedTime) < cacheage && storedTime != -1)) { // image was stored within the cacheage time.
obj[attr] = f.nativePath;
} else {
if (f.exists()) {
// It exists, now we need to delete it.
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, basedir, filename); // Now recreate it.
// create basedir if it doesn't exist.
var d = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, basedir);
if (!d.exists()) {
// retrieve remote image.
var req = Ti.Network.createHTTPClient();'GET', uri);
req.onload = function() {
if (req.status == 200) {
Ti.App.Properties.setDouble("CACHE_TIME_"+filename, now);
obj[attr] = f.nativePath;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment