Caching Assets

If your application uses dynamic downloaded assets, similar to a Facebook application displaying your contacts picture, consider caching the assets on your device. Doing so will prevent the overhead of a download every time your application initializes.

Save this technique for small files so that you don’t abuse the user’s storage capacity.

Here, we are looking at the name of the file as part of a url. Check if the file already exists on the SD card. If it does, load it locally. If it does not, get the file from a remote server and save it to the device:

[code]

import flash.display.Loader;
import flash.net.URLRequest;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
var stream:FileStream;
var fileName:String;
var file:File;
var urlLoader:URLLoader;
var url:String = “http://www.v-ro.com/cat.jpeg”;
fileName = new String(url).split(“/”).pop(); // cat.jpeg
file = File.applicationStorageDirectory.resolvePath(fileName);
if (file.exists) {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLocal);
loader.load(new URLRequest(file.url);
} else {
urlLoader = new urlLoader ();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onRemote);
loader.load(new URLRequest(url));
}
function onLocal(event:Event):void {
event.currentTarget.removeEventListener(Event.Complete, onLocal);
addChild(event.currentTarget.content);
}
function onRemote(event:Event):void {
event.target.removeEventListener(Event.COMPLETE, onRemote);
var byteArray:ByteArray = event.target.data as ByteArray;
stream.open(file, FileMode.WRITE);
stream.writeBytes(data, 0, data.length);
stream.close();
var loader:Loader = new Loader();
loader.loadBytes(byteArray);
addChild(loader);
}

[/code]


Posted

in

by

Tags: