Loading Local PDF File Into WebView

旧时模样 提交于 2019-12-30 06:55:14

问题


I am attempting to put the following functionality into an iOS app I am writing:

  • Ship a set of PDFs in the resources folder of the project in XCode
  • Copy the PDFs to the app directory
  • Open the PDF in a webview.

As far as I can see, the first two steps work ok (I've used FileManager to check fileExistsAtPath after the copy operation). However, the webview is empty, and is erroring out ("the requested URL does not exist on server"). My code for the file open is as follows:

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];

This works fine on the simulator, but doesn't work on the device


回答1:


Are you sure you don't want to let the UIDocumentInteractionController do the heavy lifting for you?

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



回答2:


As posted by Anna Karenina above, "The device is case-sensitive. Make sure the filename matches exactly"




回答3:


As bshirley suggested UIDocumentInteractionController is a great option to present your PDF. Initially I tried using the 3rd party JSQWebViewController but I was getting a blank screen on device while on simulator it was working. UIDocumentInteractionController worked great for me! For Swift you can do:

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

and implement the delegate method:

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


来源:https://stackoverflow.com/questions/7502189/loading-local-pdf-file-into-webview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!