加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

iphone – iOS下载并保存HTML文件

发布时间:2020-12-15 01:58:03 所属栏目:百科 来源:网络整理
导读:我正在尝试下载一个网页(html),然后显示已经在UIWebView中下载的本地html。 这是我试过的 – NSString *stringURL = @"url to file";NSURL *url = [NSURL URLWithString:stringURL];NSData *urlData = [NSData dataWithContentsOfURL:url];if ( urlData ){
我正在尝试下载一个网页(html),然后显示已经在UIWebView中下载的本地html。

这是我试过的 –

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”错误。

不太确定我做错了什么?

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

解决方法

传递给UIWebView的路径是不正确的,就像Freerunnering所提到的,尝试改为:

// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,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]]];

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读