Category Archives: iOS

Loading files locally from a iOS webview

Ran into this issue yesterday. I am using a webView to develop a prototype in HTML5. The problem is that my webView accesses an external file index.html. If you try and file the standard file:// protocol you will get strange security issues and the files wont load. The solution is below, basically we had to use myapp:// protocol which is defined by the iOS app.

#---- Place this by your webview

[NSURLProtocol registerClass:[NSURLProtocolCustom class]];

#---- "NSURLProtocolCustom.h"

@interface NSURLProtocolCustom : NSURLProtocol
@end

#---- "NSURLProtocolCustom.m"

#import "NSURLProtocolCustom.h"

@implementation NSURLProtocolCustom

+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest
{
    if ([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] == NSOrderedSame) {
        return YES;
    }
    return NO;
}

+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest
{
    return theRequest;
}

- (void)startLoading
{
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL 
                                                        MIMEType:@"image/png" 
                                           expectedContentLength:-1 
                                                textEncodingName:nil];

    NSMutableString *FileName  = [[self.request.URL.absoluteString stringByReplacingOccurrencesOfString:@"myapp://" withString:@""] stringByReplacingOccurrencesOfString:@".png" withString:@""]; 
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:FileName ofType:@"png"];  
    NSData *data = [NSData dataWithContentsOfFile:imagePath];

    NSLog(@"---- DATA URL"); 
    NSLog(imagePath); 

    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
}

- (void)stopLoading
{
    NSLog(@"request cancelled. stop loading the response, if possible");
}

@end