Search code examples
iosios6uiwebviewmobile-safari

Cached images in UIWebView take longer to load? (NSURLProtocol?)


I'm serving up local images to my UIWebView via NSURLProtocol (which means the image is returned almost immediately), but I'm experiencing an issue where cached images (images being displayed again after their first load) take longer to load. Is there something in my NSURLProtocol causing this?

@implementation URLProtocol

+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
    return  [request.URL.scheme isEqualToString:@"file"] ||
            [request.URL.scheme isEqualToString:@"http"];
}

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

- (void) startLoading {
    id<NSURLProtocolClient> client = self.client;
    NSURLRequest* request = self.request;
    NSString *fileToLoad = request.URL.absoluteString;
    NSURLResponse *response;

    if([fileToLoad hasPrefix:@"http://app-fullpath/"]){
        fileToLoad = [fileToLoad stringByReplacingOccurrencesOfString:@"http://app-fullpath/" withString:@""];
    } else {
        fileToLoad = [[NSURL URLWithString:fileToLoad] path];
    }

    NSData* data = [NSData dataWithContentsOfFile:fileToLoad];

    response = [[NSHTTPURLResponse alloc] initWithURL:[request URL] statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:[NSDictionary dictionary]];

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

- (void) stopLoading { }
@end

Any speed suggestions, javascript/html or iOS?


Solution

  • My problem was that UIWebView gives text a much higher priority than images, so text is laid out first, then images are processed. In order to fix that I created a DOM representation of my HTML & Images, then I replaced all images with images loaded via javascript (new Image()) and they show instantly.