HaemEternal
HaemEternal

Reputation: 2269

Loading Local PDF File Into WebView

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

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

Upvotes: 4

Views: 5330

Answers (3)

Foti Dim
Foti Dim

Reputation: 1371

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!
}

Upvotes: 0

HaemEternal
HaemEternal

Reputation: 2269

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

Upvotes: 0

bshirley
bshirley

Reputation: 8356

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

Upvotes: 1

Related Questions