Skip to content

Instantly share code, notes, and snippets.

@hansemannn
Created December 12, 2018 10:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hansemannn/c256c9a6090e2c99ca9d8f3797b14de6 to your computer and use it in GitHub Desktop.
Save hansemannn/c256c9a6090e2c99ca9d8f3797b14de6 to your computer and use it in GitHub Desktop.
Caching remote images in Titanium (asynchronously)
export default class Utils {
static loadCachedImageFromURL(url, cb) {
let filename;
try {
filename = url.substring(url.lastIndexOf('/') + 1);
} catch (err) {
cb(null);
}
const imageFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, filename);
// If already cached: load from cache
if (imageFile.exists()) {
cb(imageFile.nativePath);
return;
}
const httpClient = Ti.Network.createHTTPClient({
onload: event => {
if (!httpClient.responseData) {
Ti.API.error(event.error);
cb(null);
return;
}
imageFile.write(httpClient.responseData);
cb(imageFile.nativePath);
},
onerror: event => {
Ti.API.error('Could not load image:' + event.error);
}
});
httpClient.open('GET', url);
httpClient.send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment