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

时间:2012-01-29 17:16:46

标签: iphone xcode ipad uiwebview

我想下载一个页面并在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];
}

1 个答案:

答案 0 :(得分:4)

我一直想写几个星期,这个问题终于让我去做了。请参阅Drop-in offline caching for UIWebView (and NSURLProtocol)

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

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