将本地PDF文件加载到WebView中

我正在尝试将以下function放入我写的iOS应用程序中:

  • 在XCode的项目的资源文件夹中发送一组PDF
  • 将PDF复制到应用程序目录
  • 在webview中打开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]; 

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

你确定你不想让UIDocumentInteractionController为你付出沉重的代价吗?

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

正如上面的Anna Karenina所发布的,“设备区分大小写,确保文件名完全匹配”

正如bshirleybuild议UIDocumentInteractionController是一个很好的select来呈现您的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! }