Objective-c / iOS – 使用Safari打开本地html文件

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

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

该文件是在我的临时文件中创build的。 之后,我想在Safari中打开这个文件,但它不起作用:

 NSURL *url = [NSURL fileURLWithPath:documentPath]; [[UIApplication sharedApplication] openURL:url]; 

没有任何事情发生在屏幕上,没有错误…但是,如果我通过@“http://google.fr”replace“url”,Safari会通过google.fr启动,我可以通过inputurl来访问我的临时文件“ file://localhost…./myHtmlDocument.html“在Safari中。

希望你能帮我

您无法通过Safari打开包含在应用程序包中的文档(请参阅iOS安全模型 )。

你需要的是使用UIWebView来显示你的应用程序中的文档内容– loadHTMLString:baseURL: 例如:

 UIWebView* webView = [[[UIWebView alloc] initWithFrame:rect] autorelease]; [webView loadHTMLString:myHTMLSource baseURL:nil]; [self.view addSubview:webView]; 

我不认为你可以实现这一点,因为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];