Created
December 12, 2018 10:19
-
-
Save hansemannn/c256c9a6090e2c99ca9d8f3797b14de6 to your computer and use it in GitHub Desktop.
Caching remote images in Titanium (asynchronously)
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
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