Skip to content

Instantly share code, notes, and snippets.

Embed
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.
Usage:
var imgv = Ti.UI.createImageView({
width: 90,
height: 90,
image: 'default.png'
});
cachedImageView('bucket_name', 'http://127.0.0.1:8000/1.png', imgv, "image", 1000); // 1 second, cache expiry.
cachedImageView('bucket_name', 'http://127.0.0.1:8000/1@2x.png', 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.
f.deleteFile();
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()) {
d.createDirectory();
}
// retrieve remote image.
var req = Ti.Network.createHTTPClient();
req.open('GET', uri);
req.onload = function() {
if (req.status == 200) {
f.write(req.responseData);
Ti.App.Properties.setDouble("CACHE_TIME_"+filename, now);
obj[attr] = f.nativePath;
}
}
req.send();
}
}
@sukima

This comment has been minimized.

Copy link

commented Jan 4, 2014

The only downside is that the image will never get deleted if it is never requested again. If you were to use this to load 100 images and then never try to open them again the files would stick around for ever. Any thoughts on that?

@sukima

This comment has been minimized.

Copy link

commented Jan 5, 2014

For what it's worth I wrote a more feature full one at https://github.com/sukima/TiCachedImages which can handle cleaning out expired files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.