NOTE. This method works well with UIKit UIWebView and AppKit WebView , but does not work for the new WKWebView , which seems to ignore the URL loading system. See Comments.
Use NSURLProtocol to process local files as if they were remote requests. For a complete example, see PandoraBoy called ResourceURLProtocol . I will go through a slightly simplified version of this here. We will read http://.RESOURCE./path/to/file as if it were <resources>/path/to/file .
Each NSURLProtocol will be asked if it can handle every request that appears on the system. He should answer if it could be in +canInitWithRequest: We will say if the host is .RESOURCE. then we can process it. .RESOURCE. is an illegal DNS name, so it cannot conflict with any real host (but it is a legitimate host name for the purpose of the URL).
NSString *ResourceHost = @".RESOURCE."; + (BOOL)canInitWithRequest:(NSURLRequest *)request { return ( [[[request URL] scheme] isEqualToString:@"http"] && [[[request URL] host] isEqualToString:ResourceHost] ); }
Then we need several accounting methods. Nothing is visible here.
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { return request; } -(void)stopLoading { return; }
Now we get to the meat. startLoading is where you are going to do whatever you want to do with the request.
-(void)startLoading { NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; NSString *notifierPath = [[thisBundle resourcePath] stringByAppendingPathComponent:[[[self request] URL] path]]; NSError *err; NSData *data = [NSData dataWithContentsOfFile:notifierPath options:NSUncachedRead
I also found a bit of ResourceURL wrapper:
@implementation ResourceURL + (ResourceURL*) resourceURLWithPath:(NSString *)path { return [[[NSURL alloc] initWithScheme:@"http" host:ResourceHost path:path] autorelease]; } @end
To use it, you just need to register the protocol handler first:
[NSURLProtocol registerClass:[ResourceURLProtocol class]];
Then you can create a βresource URLβ and load it:
ResourceURL *resource = [ResourceURL resourceURLWithPath:...]; [webView loadRequest:[NSURLRequest requestWithURL:resource]];
For more information on NSURLProtocol , as well as a more sophisticated caching example, see Rollback Offline Caching for UIWebView (and NSURLProtocol) .
PandoraBoy is full of NSURLProtocol examples (look for all classes with Protocol in your names). You can capture, track, redirect or manipulate almost everything that happens through the URL loading system in this way.