JSA986 JSA986 - 3 months ago 24
iOS Question

Get URL to a PDF thats not in documents directory - UIDocumentInteractionController

I have a PDF that is dynamically generated from saved core data every time, rather than stored in the documents directory as

NSData
self.pdfData
, rendered in a
UIWebView
. Rather than using
UIActivityController
to share the PDF i'd like to use
UIDocumentInteractionController
to get a full range of sharing options. The issue is this only seems to be for saved PDF's in the documents directory.

NSURL *PDFUrl = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"pdf"];


Id rather not save it to documents directory then delete it, I was hoping for something more elegant. I tried to get the URL directly from the
UIWebview
of the PDF using
self.webView.request.mainDocumentURL
however this returns
about:blank


NSURL *PDFUrl = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"pdf"]; <-----

if (PDFUrl) {
DebugLog(@"Loading document");

self.documentController = [UIDocumentInteractionController interactionControllerWithURL:PDFUrl];
[self.documentController setDelegate:self];
[self.documentController presentPreviewAnimated:YES];
}

Answer

UIDocumentInteractionController only works with a file on the local file system. This means you must save the PDF to a file before you can use UIDocumentInteractionController.

Write the PDF data to a file in the caches folder (NSCachesDirectory), get its file URL, use the UIDocumentInteractionController, and then delete the file when complete.

Or use UIActivityViewController and pass the NSData of the PDF as the activity item.

Comments