A working method to load local PDF and HTML files on iOS
I had a lot of trouble getting this to work, and I'm hoping this post saves someone time. Some of the information that's been posted in other locations is either wrong, incomplete, or might only work on Android. By the time you read this message the information here may no longer be accurate, so here's the testing environment:
Window 7
Flash CS 5.5.0
AIR 2.7.0.19530, which was compiled on June 28, 2011
iPad 1, version 4.3.5 of iOS
Let's get started.
- On iOS, you load external PDF and HTML files using the StageWebView class.
- On Windows, StageWebView works but the HTMLLoader class is a better choice if you're creating a desktop app.
- You can also load HTML files by reading in the file's text. The information in this post is only for loading external HTML files.
- StageWebView will not load a file that's in File.applicationDirectory. All files bundled in your app are placed in File.applicationDirectory, which means you'll have to copy any external file you wish to load with StageWebView to another directory.
- So where can you copy your file? File.applicationStorageDirectory won't work. File.documentsDirectory does work.
- Several people have recommended copying to a temporary file using File.createTempFile(). This works, but there's a catch: it seems that, like Windows, StageWebView relies on a file's extension when determining how to load it. When you create a temporary file on iOS using File.createTempFile(), the file will have no extension (and on Windows, File.createTempFile() creates a file with the extension .tmp, which is equally problematic).
The solution to the file extension problem is to rename the temporary file by appending the original file's extension. AIR currently does not have a <file>.rename() function, so you'll have to do it using <tempFile>.moveTo().
Here's some code I've successfully tested several times on both iOS and Windows. The file is copied to the temp directory. The file's extension is restored by just slapping the original file name to the end of the temp file.
private function loadExternalFile():void
{
var webView = new StageWebView();
webView.stage = this.stage;
webView.viewPort = new Rectangle( 0, 0, 1024, 555 );
// Works with either html or pdf files.
// These are stored in the root of the application directory.
var fileName:String = "euei.pdf";
//var fileName:String = "euei.htm";
var sourceFile = File.applicationDirectory.resolvePath( fileName );
var workingFile = File.createTempFile();
try
{
sourceFile.copyTo( workingFile, true );
// You have to rename the temp file
var renamedTempFile:File = workingFile.resolvePath(workingFile.nativePath + fileName);
workingFile.moveTo(renamedTempFile, true);
webView.loadURL( renamedTempFile.url );
}
catch (err:Error) { }
}
