iOS 下载并保存 HTML 文件 [英] iOS download and save HTML file

查看:17
本文介绍了iOS 下载并保存 HTML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试下载网页 (html),然后在 UIWebView 中显示已下载的本地 html.

I am trying to download a webpage (html) then display the local html that has been download in a UIWebView.

这是我尝试过的-

NSString *stringURL = @"url to file";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
    NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];  

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"index.html"];
    [urlData writeToFile:filePath atomically:YES];
}

    //Load the request in the UIWebView.
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];        // Do any additional setup after loading the view from its nib.

但这会产生SIGABRT"错误.

But this gives a 'SIGABRT' error.

不太确定我做错了什么?

Not too sure what I have done wrong?

任何帮助将不胜感激.谢谢!

Any help would be appreciated. Thanks!

推荐答案

传递给 UIWebView 的路径不正确,就像 Freerunnering 提到的,试试这个吧:

The path passed to the UIWebView is incorrect, like Freerunnering mentioned, try this instead:

// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"];   

// Download and write to file
NSURL *url = [NSURL URLWithString:@"http://www.google.nl"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

// Load file in UIWebView
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];      

注意:需要添加正确的错误处理.

Note: Correct error-handling needs to be added.

这篇关于iOS 下载并保存 HTML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆