You want to load an asset from a URL and store it for use when the application is offline.
Use the File I/O API to save the requested asset to the application's store and read that file on subsequent requests.
In this example, we will load an XML file that is at a known URL. Once the data has been loaded, it will be saved to the local disk, and on subsequent requests for the document it will be loaded from the local disk instead of from the remote location.
First, we will use the XMLHttpRequest object to load the XML data from the remote location. The XMLHttpRequest.open() method takes three arguments. The first argument is the method of the HTTP request that is being made. The second argument is the URI of the location of the data being loaded. The third argument is a Boolean that specifies whether the operation will be asynchronous.
Once we have specified these arguments in the open method, we will call the send method. The send method takes a single argument that contains the content that is to be sent with the request. In our case, we won't send any data with the request:
var xml = new XMLHttpRequest(); xml.open( "GET", "http://www.foo.com/data.xml", true );
xml.send( null );
Because we are loading the data asynchronously, we need to create a handler for the response which is called once the data has loaded from the server. This handler will be added before the send method is called. Within this handler, we will save the data that is located in the responseText property of the XMLHttpRequest instance to a known location on the local filesystem for retrieval in subsequent requests. We cover reading and writing text to the local system elsewhere in the book, and therefore we won't cover it in detail here:
xml.onreadystatechange = function()
{
if( xml.readyState == 4 ) // the request is complete
{
// write the data to the local system
var file = air.File.applicationStorageDirectory.resolvePath("data.xml");
var fileStream = new air.FileStream();
fileStream.open( file, air.FileMode.WRITE );
fileStream.writeMultiByte( xml.responseText, air.File.systemCharset );
fileStream.close();
}
}
Before each request of the data, we will need to check whether the data.xml file exists. If it exists, we do not need to load the file using the XMLHttpRequest object and can use the File API to load it from the disk. This allows us to load the data even if the user is not currently online:
var data = null;
var file = air.File.applicationStorageDirectory.resolvePath("data.xml");
if( file.exists )
{
var fileStream = new air.FileStream();
fileStream.open( file, air.FileMode.READ );
data = fileStream.readMultiByte( fileStream.bytesAvailable, air.File.systemCharset );
fileStream.close();
}
else
{
// read the data via XMLHttpRequest and write that
// data to the file system
}
This cookbook example was originally posted in the Adobe AIR for JavaScript Developers Pocketguide, which can currently be found at toString.org.
+