iOS下载并保存HTML文件

Ave*_*Pro 17 iphone xcode uiwebview ios4 ios

我正在尝试下载网页(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.
Run Code Online (Sandbox Code Playgroud)

但这会产生'SIGABRT'错误.

不太确定我做错了什么?

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

Ann*_*nne 23

传递给UIWebView的路径不正确,就像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]]];      
Run Code Online (Sandbox Code Playgroud)

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


Kea*_*b42 8

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

  • 最好是评论. (2认同)