Hi all,

I'm trying to design a custom caching mechanism for a UIWebView. When the first 
URL request is loaded, it spawns further URL requests for loading graphics. As 
the user clicks links etc, it loads more URL requests.

I can use a subclass of NSURLCache to intercept requests for cached data:

@interface BFWURLCache : NSURLCache

@end

@implementation BFWURLCache

- (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request
{
        NSCachedURLResponse* cachedResponse = nil;
        NSString* cachePath = [self cachePathForRequest:request];
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath])
        {
                DLog(@"using cached: %@", cachePath);
                NSURL* cacheURL = [NSURL fileURLWithPath:cachePath];
                NSURLResponse* urlResponse = [[NSURLResponse alloc] 
initWithURL:cacheURL MIMEType:nil expectedContentLength:1 textEncodingName:nil];
                cachedResponse = [[NSCachedURLResponse alloc] 
initWithResponse:urlResponse data:[[NSFileManager defaultManager] 
contentsAtPath:cachePath]];
                [urlResponse release];
                [cachedResponse autorelease];
        }
        else
        {
                DLog(@"caching: %@", request.URL);
                [self queueRequest:request];
        }
        return cachedResponse;
}

@end

Then in my AppDelegate, I tell the app to use my custom cache:

        [NSURLCache setSharedURLCache:[[[BFWURLCache alloc] 
initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]] autorelease];

That works fine for intercepting URL requests in any web view. If the 
corresponding file exists at cachePath, it is given as a response to the 
request.

However, if the cachePath file does not already exist (ie has not been cached 
yet), my queueRequest method fires off a new NSURLConnection with the request, 
downloads the file into the cachePath. Since this takes time (in another 
thread), I don't have any cachedResponse ready to return from the 
cachedResponseForRequest call, so it just returns nil. The UIWebView sees the 
nil return (ie nothing cached) and so proceeds to load the URL itself. So now I 
have two processes loading the same URL: The web view and the custom caching 
mechanism.

How can I intercept URL requests from UIWebViews, including spawned requests 
and customise the responses? Is overriding NSURLCache (as above) the only way? 
If so, how can I get at the data of the response when it is first loaded (so I 
don't have to download it separately)?

Thanks,
Tom

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to