Search code examples
ios6uiwebviewasihttprequestuiweb

loading cached webpage in UIWebView in ios


I've a task that increasing speed of webpage loading in UIWebView. For that I'm moving to cache concept. Here I'm using ASIWebPageRequest to cache all the content of the webpage. Its doing well.But when load the cached webpage, the hyperlinks are not working(not linking with live url)?

and another one. If the webpage is cached means,its loads from cache otherwise loads from live url. How can I fix it?

Here is my code:

- (void)fetchURL:(NSURL *)url
{

    [self setRequestsInProgress:[NSMutableArray array]];

    [request setDelegate:nil];
    [request cancel];
    [self setRequest:[ASIWebPageRequest requestWithURL:url]];

    [request setDidFailSelector:@selector(webPageFetchFailed:)];
    [request setDidFinishSelector:@selector(webPageFetchSucceeded:)];
    [request setDelegate:self];
    [request setDownloadProgressDelegate:self];
    [request setUrlReplacementMode:ASIReplaceExternalResourcesWithData];



    [request setDownloadCache:[ASIDownloadCache sharedCache]];
    [request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];

    // This is actually the most efficient way to set a download path for ASIWebPageRequest, as it writes to the cache directly
    [request setDownloadDestinationPath:[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:request]];

    [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
    [request startAsynchronous];
}


- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
{
    NSLog(@"fetch error = %@",[theRequest error]);
}

- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
{
    NSURL *baseURL;
    if ([request isFinished] ) {


        baseURL = [NSURL fileURLWithPath:[request downloadDestinationPath]];


        //        // If we're using ASIReplaceExternalResourcesWithLocalURLs, we must set the baseURL to point to our locally cached file
    } else {
        baseURL = [request url];
    }

    if ([theRequest downloadDestinationPath]) {

        NSString *response = [NSString stringWithContentsOfFile:[theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];

        [webView loadHTMLString:response baseURL:baseURL];


    } else {

        [webView loadHTMLString:[theRequest responseString] baseURL:baseURL];
    }


}

Solution

  • Change this line

    [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
    

    to

    [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:YES];
    

    It will work