iOS下载并保存HTML文件

我试图下载一个网页(HTML),然后显示已下载的本地HTML在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'错误。

不太确定我做错了什么?

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

传递给UIWebView的path是不正确的,就像Freerunnering提到的那样,试试这个:

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

注意:需要添加正确的error handling。

NSDocumentDirectory将备份到iCloud。 你可能会更好使用NSCachesDirectory https://developer.apple.com/library/ios/#qa/qa1719/_index.html

您的应用程序是一个扩展名为.app的文件夹。 在安装iPhone之后,您不能更改此文件夹,因此为什么将其保存到文档目录。

在你的示例代码中,将文件保存到Documents / index.html,并要求它加载appname.app/index.html。

[NSBundle mainBundle]没有给你的文件目录,它给你(我认为).app文件夹(尽pipe它可能是包含应用程序,文档和其他文件夹的文件夹)。

给你想要改变这一行。

 [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]]; 

要(提供这个方法和其余的代码是一样的,否则重新创build对象'filePath')

 [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath isDirectory:NO]]]; 

这是Swift 2.x版本:

  var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) var filePath: String = "\(paths[0])/\("index.html")" // Download and write to file var url: NSURL = NSURL(string: "http://www.google.nl")! var urlData: NSData = NSData.dataWithContentsOfURL(url) urlData.writeToFile(filePath, atomically: true) // Load file in UIWebView web.loadRequest(NSURLRequest(URL: NSURL.fileURLWithPath(filePath)))