Xcode UIWEBVIEW下载,保存HTML文件并显示
问题描述:
我想下载一个页面并在WEBVIEW本地显示,但图像丢失。只有在线时才显示图像,而在离线模式下,图像不见了。我该如何解决这个问题?这是我用直到现在代码:Xcode UIWEBVIEW下载,保存HTML文件并显示
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
NSURL *url = [NSURL URLWithString:@"http://livedemo00.template-help.com/wt_37587/index.html"];
//[WEBVIEW loadRequest:reqURL];
// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"];
// Download and write to file
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
// Load file in UIWebView
[WEBVIEW loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
[super viewDidLoad];
}
答
我一直现在写这个了几个星期,这个问题终于得到了我这样做。请参阅Drop-in offline caching for UIWebView (and NSURLProtocol)。
简短的回答,在我的经验,这是最简单的解决方法是使用一个NSURLProtocol
拦截NSURLConnection
请求(包括UIWebView
制作的成品),并将结果写入到磁盘。如果请求是在脱机时完成的,那么只需从磁盘读取响应并重播。这对于其他应用程序来说是非常透明的,并且避免了与子类NSURLCache
相关的各种边缘案例。 (有关如何继承的更多信息NSURLCache
看Substituting local data for remote UIWebView requests上可可的爱,和AFCache。)
我NSURLProtocol
做法很简单,而不是通用的缓存解决方案。它只是用于在脱机时协助UIWebView
。但为此,我认为它很好地解决了这个问题。