-
-
Save jeffatstepup/1662753 to your computer and use it in GitHub Desktop.
Appcelerator Titanium ImageView /w cache and cacheage. Supports retina display.
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
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/[email protected]', 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment