OSDir


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Persisting ContentCache to disk between sessions


Erik,

How do the icons and logos get into the cache in the first place?  If they don't change, is there any reason not to embed them in the application?

-Alex

On 10/26/18, 3:36 PM, "Erik J. Thomas" <erik@xxxxxxxxxx> wrote:

    Hey all:
    
    Have any of you come across an example of persisting a ContentCache to disk and reading it back on app launch? We have lots of icons and logos for hundreds of companies and they don't change between sessions. 
    
    Like this (doesn't work though). ImageCache is a subclass of ContentCache to get access to the protected cachedData:Dictionary which is key/value pairs, with key as URL to image, and value is bitmapData.
    
    public function saveImageCache(imageCache:ImageCache):void {
       var cacheFile:File = File.applicationStorageDirectory;
       cacheFile = cacheFile.resolvePath(IMAGE_CACHE_FILE_NAME);
       if (cacheFile.exists) {
          cacheFile.deleteFile();
       }
       var fileStream:FileStream = new FileStream();
       fileStream.open(cacheFile, FileMode.WRITE);
       fileStream.writeObject(imageCache.getEntries()); // this is a Dictionary with byte array for image as value
       fileStream.close();
    }
    
    The writeObject API of FileStream does not marshal the bitmapData to disk. 
    
    /**
     * Loads a persisted image cache from disk.
     *
     * @return ContentCache
     */
    public function loadImageCache():ImageCache {
       var cacheFile:File = File.applicationStorageDirectory;
       cacheFile = cacheFile.resolvePath(IMAGE_CACHE_FILE_NAME);
       if (cacheFile.exists) {
          var fileStream:FileStream = new FileStream();
          fileStream.open(cacheFile, FileMode.READ);
          var entries:Dictionary = fileStream.readObject() as Dictionary;
          fileStream.close();
          var imageCache:ImageCache = new ImageCache();
          imageCache.loadEntries(entries);
          return imageCache;
       }
       return null;
    }
    
    The entries variable does populate with all the keys as URLs, but the values are null. FileStream won't read just raw binary data in this way.
    
    I don't want to have to save every image using an encoder into separate files and then load them all back if I can help it. 
    
    Just seems FileStream should be able to just write a blob of binary data to disk and retrieve it "as-is" but it doesn't or I can't find the way.
    
    Thanks for your suggestions.
    
    Erik