Asset Caching

author:
Daniel Sperl
description:
Cache remote assets in a local directory.
compatible:
v2.4
tag:
assets, cache
homepage:
https://gist.github.com/PrimaryFeather/a08cda0c75ae8ff7a660d76cc391628f

Overview

This extension requires Starling 2.4 with its new AssetManager. Furthermore, it only works with AIR (not in the Flash Player).

If your application or game loads assets (e.g. textures) from the server each time it starts, it makes sense to cache these files locally. This extension does just that. Once an asset has been downloaded, it is cached in the “cacheDirectory” of the current device; the next time the same asset is required, it's loaded directly from disk.

The extension is actually a subclass of Starling's starling.assets.DataLoader class. That class is used by the AssetManager to fetch binary data from a server or a file. Assign an instance of the CachingDataLoader to enable automatic caching.

var assets:AssetManager = new AssetManager();
assets.dataLoader = new CachingDataLoader(); // <-- here
assets.enqueue(/* ... */);
assets.loadQueue(/* ... */);

That's it!

The class, as it's provided here, contains a few “trace” statements that will tell you if data is loaded or stored to the cache. You can safely remove them, of course.

Caching Zipped Assets

This extension can easily be combined with the Zipped-Assets extension. You just need to change the base class of the ZipLoader, like here:

// before:
public class ZipLoader extends DataLoader
 
// after:
public class ZipLoader extends CachingDataLoader

Now, when you assign the ZipLoader to the AssetManager's dataLoader property, it will cache the zip files locally, and then extract them on the fly.

Changelog

Source Code

%gist(a08cda0c75ae8ff7a660d76cc391628f)%

User Comments

Feel free to edit this part of the page if you want to add information that's lacking in the above description.
Questions are better asked in the forum, though.