Archive for June, 2008

Select and access local SWF files within an AIR application

Well, it took me a little time to figure out how to select and load a local SWF file into an SWFLoader instance. Several times I got this error message:

“SecurityError: Error #3015: Loader.loadBytes() is not permitted to load content with executable code.”

After some research I found this "dreaming in flash" blog entry which basically contains the solution I was looking for.

But then it took me a little more time to figure out how to use this with the SWFLoader. So here is a basic code example:

Actionscript:
  1. import flash.display.Loader;
  2. import flash.filesystem.File;
  3. import flash.filesystem.FileMode;
  4. import flash.filesystem.FileStream;
  5. import flash.system.LoaderContext;
  6. import flash.utils.ByteArray;
  7. import mx.controls.SWFLoader;
  8.  
  9. // File reference
  10. var swfFile: File;
  11.  
  12. // Open the SWF file
  13. var fileStream: FileStream = new FileStream();
  14.     fileStream.open( swfFile, FileMode.READ );
  15.  
  16. // Read SWF bytes into byte array and close file
  17. var swfBytes: ByteArray = new ByteArray();
  18.     fileStream.readBytes( swfBytes );
  19.     fileStream.close();
  20.  
  21. // Prepare the loader context to avoid security error
  22. var loaderContext: LoaderContext = new LoaderContext();
  23.     loaderContext.allowLoadBytesCodeExecution = true; // that's it!
  24.    
  25. // Now you could use this with a Loader instance
  26. var loader: Loader = new Loader();
  27.     loader.loadBytes( swfBytes, loaderContext );
  28.    
  29. // Or you could use this with a SWFLoader instance
  30. var swfLoader: SWFLoader = new SWFLoader();
  31.     swfLoader.loaderContext = loaderContext;
  32.     swfLoader.source = swfBytes;