Skip to content

Instantly share code, notes, and snippets.

@func09
Created April 20, 2011 10:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save func09/930962 to your computer and use it in GitHub Desktop.
Save func09/930962 to your computer and use it in GitHub Desktop.
TitaniumのImageViewでリモートURLの画像を永続的にキャッシュする
$$$ = {};
$$$.ui = {};
$$$.ui.createImageView = function(options){
var ui = Ti.UI.createImageView(options);
// 画像を永続化してキャッシュ
ui.imageWithCache = function(url){
url = url.replace(/\?[0-9]+$/,'');
var cacheFilePath = Titanium.Filesystem.applicationDataDirectory + '/' + hex_sha1(url);
var cacheFile = Ti.Filesystem.getFile(cacheFilePath);
if ( cacheFile.exists()) {
// キャッシュがある場合
Ti.API.info('画像キャッシュファイルあり : ' + cacheFilePath + ' [' + cacheFile.modificationTimestamp() + ']');
ui.image = cacheFilePath;
} else {
// キャッシュがない場合
Ti.API.info('画像キャッシュファイル作成 : ' + cacheFilePath);
ui.addEventListener('load', function(e){
cacheFile = Ti.Filesystem.getFile(cacheFilePath);
if ( !cacheFile.exists()) { // すでに作成されている可能性もあるので
cacheFile.write(ui.toBlob());
}
});
ui.image = url;
}
}
return ui;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment