【问题标题】:Objective-c/iOS - Open local html file with SafariObjective-c/iOS - 用 Safari 打开本地 html 文件
【发布时间】:2013-09-18 22:52:12
【问题描述】:

我有一个 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 启动,我可以通过键入 url“file://localhost..../”来访问我的临时文件myHtmlDocument.html”在 Safari 中。

希望你能帮助我

【问题讨论】:

  • 如果您的 iOS 设备有互联网连接,请将其放在网络上并打开它

标签: objective-c ios cocoa-touch safari


【解决方案1】:

您无法通过 Safari 打开包含驻留在您的应用程序包中的文档(请参阅iOS Security Model)。

您需要使用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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      相关资源
      最近更新 更多