Xcode UIWEBVIEW 下载,保存 HTML 文件并显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9055050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:08:42  来源:igfitidea点击:

Xcode UIWEBVIEW download , save HTML file and show

iphonexcodeipaduiwebview

提问by user1175380

I want to download a page and show this in WEBVIEW local, but the images are missing. The images are only shown, when I'm online, in offline mode they are missing. How can I solve this? This is the code I used up until now:

我想下载一个页面并在本地 WEBVIEW 中显示此页面,但缺少图像。图像仅在我在线时显示,在离线模式下它们会丢失。我该如何解决这个问题?这是我到目前为止使用的代码:

// 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];
}

回答by Rob Napier

I've been meaning to write this up for a few weeks now, and this question finally got me to do it. See Drop-in offline caching for UIWebView (and NSURLProtocol).

几个星期以来我一直想写这个,这个问题终于让我去做了。请参阅UIWebView(和 NSURLProtocol)的嵌入式离线缓存

The short answer, in my experience, is that the easiest solution is to use an NSURLProtocolto intercept NSURLConnectionrequests (including the ones made by UIWebView) and write the results to disk. If the request is made when you're offline, just read the response from disk and replay it. This is extremely transparent to the rest of the application, and avoids all kinds of edge-cases related to subclassing NSURLCache. (For more information on how to subclass NSURLCachesee Substituting local data for remote UIWebView requestson Cocoa With Love, and AFCache.)

根据我的经验,简短的回答是,最简单的解决方案是使用 anNSURLProtocol来拦截NSURLConnection请求(包括由 发出的请求UIWebView)并将结果写入磁盘。如果请求是在您离线时发出的,只需从磁盘读取响应并重播即可。这对应用程序的其余部分非常透明,并避免了与子类化相关的各种边缘情况NSURLCache。(有关如何子类化的更多信息,NSURLCache请参阅Cocoa With Love 和AFCache上的远程 UIWebView 请求替换本地数据。)

My NSURLProtocolapproach is very simple, and is not a general-purpose caching solution. It's just intended to assist a UIWebViewwhen you're offline. But for that, I think it solves the problem well.

我的NSURLProtocol方法很简单,并不是通用的缓存解决方案。它只是为了UIWebView在您离线时提供帮助。但为此,我认为它很好地解决了问题。