Objective-C/iOS - 使用Safari打开本地HTML文件

3

我有一个保存在临时目录中的HTML文件,像这样:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentDirectory = NSTemporaryDirectory();
NSString *documentPath = [documentDirectory stringByAppendingPathComponent:@"mydocument.html"];
[fileManager createFileAtPath:documentPath contents:myHTMLDocumentData attributes:nil];

文档已创建在我的临时文件中。之后,我想在Safari中打开此文档,但无法正常工作:
NSURL *url = [NSURL fileURLWithPath:documentPath];
[[UIApplication sharedApplication] openURL:url];

屏幕上没有任何反应,也没有出现错误... 然而,如果我将"url"替换为@"http://google.fr",Safari会启动并显示google.fr,我可以通过在Safari中输入"url file://localhost..../myHtmlDocument.html"来访问我的临时文件。 希望我能帮到你。

如果您的iOS设备具有互联网连接功能,请将其放在网络上并打开它。 - bshirley
2个回答

8
您无法通过Safari打开存储在应用程序包中的文档(请参见iOS安全模型)。
您需要使用UIWebView,通过- loadHTMLString:baseURL:在应用程序内显示文档内容; 例如:
UIWebView* webView = [[[UIWebView alloc] initWithFrame:rect] autorelease];
[webView loadHTMLString:myHTMLSource baseURL:nil];
[self.view addSubview:webView];

2

我不认为你能实现这个,因为UIApplication openURL:和UIDocumentInteractionController都不能打开你包内的本地文件。

相反,在你的viewDidLoad中执行以下操作:

UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self addSubview:webView];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath: documentPath]];
[webView loadRequest:request];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接