phoboslab/Ejecta — pull request #346 by aogilvie (2014-03-04 09:57:08+00:00)
Title: check cache resource before bundle resource

#### Feature

Allows cache files to be loaded from `- (NSString *)pathForResource:(NSString *)path`.

*Example use case:* A game asset management system downloads new versions of images to cache folder. The game code automatically gets the latest image using a relative path (`image/water.png`) inside Ejecta.

(Optionally) If this behaviour is too much logic for Ejecta's `pathForResource` then allowing `pathForResource` to take FULL paths instead of relative to main bundle only;

e.g. `file:///var/application/24523-5wgv-234v-32/Library/Cache/App/img/cards/card001.jpg`

#### Testing

In the demo `index.js` replace `setInterval( animate, 16 );` with

var img = new Image();
img.onload = function () {
ctx.drawImage(img, 50, 50);
}
img.src = "darth-vader.jpg";

and set `ctx.globalAlpha = 1;`

In `AppDelegate.m` `didFinishLaunchingWithOptions` add the following code to download a sample image to the cache folder:

NSString *urlString = @"http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg";

NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];

if (downloadedData) {

// Store in cache
NSString* cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *file = [cachesDirectory stringByAppendingPathComponent:@"App/darth-vader.jpg"];

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr createDirectoryAtPath:[NSString stringWithFormat:@"%@%@", cachesDirectory, @"/App"] withIntermediateDirectories:YES attributes:nil error: NULL] == YES) {
[downloadedData writeToFile:file atomically:YES];
}
}