将本地PDF文件加载到WebView中

时间:2011-09-21 15:10:49

标签: ios uiwebview

我正在尝试将以下功能放入我正在编写的iOS应用中:

  • 在XCode
  • 项目的资源文件夹中发送一组PDF
  • 将PDF复制到app目录
  • 在网页浏览中打开PDF。

据我所知,前两个步骤正常(我在复制操作后使用FileManager检查fileExistsAtPath)。 但是,webview为空,并且错误输出(“请求的URL在服务器上不存在”)。 我打开文件的代码如下:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                          NSUserDomainMask, YES);
NSString *localDocumentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = @"example.pdf";
NSString *localDocumentsDirectoryPdfFilePath = [localDocumentsDirectory  
                                     stringByAppendingPathComponent:pdfFileName];
pdfUrl = [NSURL fileURLWithPath:localDocumentsDirectoryPdfFilePath];
[webView loadRequest:[NSURLRequestWithURL:pdfUrl];

这在模拟器上工作正常,但在设备上不起作用

3 个答案:

答案 0 :(得分:1)

你确定你不想让UIDocumentInteractionController为你做繁重的工作吗?

UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
dc.delegate = self;
[dc presentPreviewAnimated:YES];

答案 1 :(得分:0)

由Anna Karenina发布,“设备区分大小写。请确保文件名完全符合”

答案 2 :(得分:0)

正如 bshirley 建议 UIDocumentInteractionController 是展示PDF的绝佳选择。最初我尝试使用第三方 JSQWebViewController ,但我在设备上得到一个空白屏幕,而在模拟器上它正在工作。 UIDocumentInteractionController 对我很有用!对于 Swift ,你可以这样做:

let interactionController = UIDocumentInteractionController(url: fileURL)
interactionController.delegate = self
interactionController.presentPreview(animated: true)

并实现委托方法:

// Mark: UIDocumentInteractionControllerDelegate
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    return UIApplication.shared.keyWindow!.rootViewController!
}