我使用ASIWebPageRequest来缓存网页。您将拥有相当多的东西(图像、javascript 等)。看我的代码。
在你的头文件中:
@property (retain, nonatomic) ASIWebPageRequest *aSIRequest;
在您的实现文件中:
//--------------------------------------------------------------------
-(void) loadContent {
//use ASIWebPageRequest to load content from web and cache, or to load already cached content.
//the content will get downloaded each time the internet will be reachable, so
//the webpage cache will will always be up to date
NSURL *url = [NSURL URLWithString:url_to_your_webpage];
[self setASIRequest:[ASIWebPageRequest requestWithURL:url]];
[self.aSIRequest setDelegate:self];
[self.aSIRequest setDidFailSelector:@selector(webPageFetchFailed:)];
[self.aSIRequest setDidFinishSelector:@selector(webPageFetchSucceeded:)];
[self.aSIRequest setUrlReplacementMode:ASIReplaceExternalResourcesWithData];
[self.aSIRequest setDownloadCache:[ASIDownloadCache sharedCache]];
[self.aSIRequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
self.aSIRequest.cachePolicy = ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy;
[self.aSIRequest setDownloadDestinationPath:
[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self aSIRequest]]];
[self.aSIRequest startAsynchronous];
}
//--------------------------------------------------------------------
- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest{
//this will generally get called if there is no data cached and no internet connection
//or other damn reason.
//let the user retry loading the content
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error!" message:@"Failed to load the content." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
[alert show];
[alert release];
}
//--------------------------------------------------------------------
- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest{
//load the webview with the downloaded or cashed content
NSString *response = [NSString stringWithContentsOfFile: [theRequest downloadDestinationPath] encoding:[self.aSIRequest responseEncoding] error:nil];
[youWebView loadHTMLString:response baseURL:[self.aSIRequest url]];
}
//--------------------------------------------------------------------
- (void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if(buttonIndex == 1){//retry button tapped
[self performSelector:@selector(loadContent) withObject:nil afterDelay:0.2];
}
else{//cancel button tapped
//do nothing.
//alternatively, you could lead the user to home screen or perform any else action
}
}
//--------------------------------------------------------------------