我正在尝试下载一个网页( 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‘错误。
不太确定我做错了什么?
任何帮助都将不胜感激。谢谢!
发布于 2011-04-10 02:58:30
传递给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]]];
注意:需要添加正确的错误处理。
发布于 2012-03-22 19:24:12
NSDocumentDirectory将备份到iCloud。您最好使用NSCachesDirectory https://developer.apple.com/library/ios/#qa/qa1719/_index.html
发布于 2011-04-10 02:53:02
你的应用程序是一个文件夹,末尾有一个.app扩展名。在iPhone上,一旦安装,您就不能更改此文件夹,因此需要将其保存到documents目录。
在示例代码中,您将文件保存到Documents/index.html并要求它加载appname.app/index.html。
NSBundle mainBundle不会给你提供文档目录,它给你的是(我认为) .app文件夹(尽管它可能是包含应用程序、文档和其他文件夹的文件夹)。
给出你想要改变这一行。
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
To (假设这是与其余代码相同的方法,否则重新创建对象'filePath')
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath isDirectory:NO]]];
https://stackoverflow.com/questions/5606915
复制相似问题