Search code examples
iosobjective-cuiwebviewnsurlcache

Ios Intercept UIWebview request via NSURLCache and replace the response


I'm developing an Epub Reader for Ios, notice that i don't use any epub library and i parse the epub myself.

I needed a method for loading resource from epub into the UIWebView, for example images or CSS file ... (resource that requested in the html files).

for this purpose i decided to use NSURLCache class and override it's method (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request

so i can intercept the request and find the right data from epub then create a NSCachedURLResponse and return it.

so far so good. BUT the the problem is that the data (i.e images) wont show in the webview. look at below code:

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    /*
    the request.URL is something like this applewebdata://UUID/OEBPS/Images/cover.jpg ,
    so the getResourcePathFromRequest give me the path OEBPS/Images/cover.jpg,
    so i can find the right data in epub
    */
    NSString *resourcePath = [self getResourcePathFromRequest:request.URL];
    /*
    ResourceResponse is a class contaning data and mimeType, 
    i tested this and the data and mimeType are good so this is not the problem
    */
    ResourceResponse *response = [[self getBook] fetch:resourcePath];

    NSURLResponse *urlResponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:response.mMimeType expectedContentLength:[response.mData length] textEncodingName:@"UTF-8"];
    NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlResponse data:response.mData];

    return cachedResponse;
}

at this point everything looks normal, the method getting called, the right data being found and the response object return, but it wont load the image into the webview.

so what is the problem?

tnx in advance.

NOTE: i'm new in ios programming world (coming from android:)


Solution

  • I loaded the data with base url (http://localhost) and everything went fine.