如何在iOS中缓存带有图片的整个网页

15
我正在iOS上开发一个图片和文本混合页面。我知道可以使用UIWebView来实现这个目标。但问题是,用户可能需要离线阅读该页面。 对于文本部分,我可以将html保存到磁盘并在离线模式下加载它。 但图片如何处理呢?是否可以将图片缓存到磁盘中,使UIWebView仍能够显示它们? 谢谢!
1个回答

15

ASIHTTPRequest项目有一个名为ASIWebPageRequest的类,旨在实现您想要的功能。如果您可以接受将额外的依赖项添加到您的项目中,则我认为这是一个很好的解决方案:ASIWebPageRequest

在我上面喜欢的页面上,有一些很好的示例说明如何使用它,但为了完整起见,我将在此处包含其中一个示例:

- (IBAction)loadURL:(NSURL *)url
{
   // Assume request is a property of our controller
   // First, we'll cancel any in-progress page load
   [[self request] setDelegate:nil];
   [[self request] cancel];

   [self setRequest:[ASIWebPageRequest requestWithURL:url]];
   [[self request] setDelegate:self];
   [[self request] setDidFailSelector:@selector(webPageFetchFailed:)];
   [[self request] setDidFinishSelector:@selector(webPageFetchSucceeded:)];

   // Tell the request to embed external resources directly in the page
   [[self request] setUrlReplacementMode:ASIReplaceExternalResourcesWithData];

   // It is strongly recommended you use a download cache with ASIWebPageRequest
   // When using a cache, external resources are automatically stored in the cache
   // and can be pulled from the cache on subsequent page loads
   [[self request] setDownloadCache:[ASIDownloadCache sharedCache]];

   // Ask the download cache for a place to store the cached data
   // This is the most efficient way for an ASIWebPageRequest to store a web page
   [[self request] setDownloadDestinationPath:
      [[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self request]]];

   [[self request] startAsynchronous];
}

- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
{
   // Obviously you should handle the error properly...
   NSLog(@"%@",[theRequest error]);
}

- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
{
   NSString *response = [NSString stringWithContentsOfFile:
      [theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
   // Note we're setting the baseURL to the url of the page we downloaded. This is important!
   [webView loadHTMLString:response baseURL:[request url]];
}

非常感谢您提供的示例,稍后会尝试一下。您能告诉我ASIReplaceExternalResourcesWithData如何将数据嵌入到页面中吗?页面在缓存中仍然是一个HTML文件,对吧?这个请求会修改原始的HTML吗? - mr.pppoe
没错,ASI会修改页面并用Data URIs替换这些资源。或者,您可以使用另一种名为ASIReplaceExternalResourcesWithLocalURLs的不同URL替换模式,它将把资源下载为文件,但仍会修改HTML以指向这些本地文件。 - xoebus
谢谢xoebus。我还发现要启用离线浏览,我需要添加这行代码:request.cachePolicy = ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy; - Joseph Lin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接