Loading Zip-Files with the AssetManager

Per default, the AssetManager cannot work with Zip-Files. However, you can add this functionality yourself by extending the class. As luck would have it, the sample class below does just that.

import flash.utils.ByteArray;
 
import nochump.util.zip.ZipEntry;
import nochump.util.zip.ZipFile;
 
import starling.utils.AssetManager;
 
public class ZipAssetManager extends AssetManager
{
    private static var zipRegEx:RegExp = /\.zip$/;
 
    public function ZipAssetManager(scaleFactor:Number=1, useMipmaps:Boolean=false)
    {
        super(scaleFactor, useMipmaps);
    }
 
    override protected function getName(rawAsset:Object):String
    {
        if (rawAsset is String)
            return super.getName(removeZipExtension(rawAsset as String));
        else
            return super.getName(rawAsset);
    }
 
    override protected function getExtensionFromUrl(url:String):String
    {
        return super.getExtensionFromUrl(removeZipExtension(url));
    }
 
    override protected function transformData(data:ByteArray, url:String):ByteArray
    {
        if (url.match(zipRegEx) != null)
        {
            var zipFile:ZipFile = new ZipFile(data);
            var entry:ZipEntry = zipFile.entries[0];
            return zipFile.getInput(entry);
        }
        else return super.transformData(data, url);
    }
 
    // helpers
 
    private static function removeZipExtension(filename:String):String
    {
        return filename.replace(zipRegEx, "");
    }
}

As you can see, the class is actually rather simple: it overrides the methods that parse the asset name or the file extension, so that they are blind about the “.zip” ending. Then it transforms the zipped ByteArray so that the AssetManager continues its work with the uncompressed data.

There's one caveat, though: Starling 1.5 unfortunately has the method “getExtensionFromUrl” still declared as “private”. You have to change that to “protected” (or use the head revision of Starling). In Starling 1.6, this will be fixed, of course.

Now, happy zipping, everyone!