Now in your HTML you can use:
<img src='localimg://myimage.png' />
This will retrieve the file locally.
| #import "AppDelegate.h" | |
| #import "LMURLImageProtocol.h" | |
| @implementation AppDelegate | |
| - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions | |
| { | |
| [NSURLProtocol registerClass:[LMURLImageProtocol class]]; | |
| // etc | |
| } |
| #import <Foundation/Foundation.h> | |
| #define kProtocolImageUrl @"localimg" | |
| @interface LMURLImageProtocol : NSURLProtocol | |
| @end |
| #import "LMURLImageProtocol.h" | |
| @implementation LMURLImageProtocol | |
| + (BOOL)canInitWithRequest:(NSURLRequest *)request{ | |
| if ([request.URL.scheme caseInsensitiveCompare:kProtocolImageUrl] == NSOrderedSame) { | |
| return YES; | |
| } | |
| return NO; | |
| } | |
| + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request{ | |
| return request; | |
| } | |
| - (void)startLoading{ | |
| NSString *extension; | |
| NSString *imageName; | |
| [self extractImageName:&imageName extension:&extension]; | |
| NSURLResponse *response =[[NSURLResponse alloc]initWithURL:self.request.URL | |
| MIMEType:nil expectedContentLength:-1 | |
| textEncodingName:nil]; | |
| NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:extension]; | |
| NSData *data = [NSData dataWithContentsOfFile:imagePath]; | |
| [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; | |
| [[self client] URLProtocol:self didLoadData:data]; | |
| [[self client] URLProtocolDidFinishLoading:self]; | |
| } | |
| -(void)extractImageName:(NSString**)imageName extension:(NSString**)extension{ | |
| NSString *urlString = self.request.URL.absoluteString; | |
| *extension = [urlString pathExtension]; | |
| urlString = [urlString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@://",kProtocolImageUrl] | |
| withString:@""]; | |
| *imageName = [urlString stringByDeletingPathExtension]; | |
| } | |
| - (void)stopLoading | |
| { | |
| } | |
| @end |