I have a PDF that I'm pulling from a sever that came in the form of NSData and now I need to display it. I've looked far and wide for a solution to this and I haven't found anything that bridges the gap between raw NSData and actually saving or showing the PDF.
I tried this but now I'm stuck not knowing how to save or show:
let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(data.bytes), data.length)
let cgDataProvider = CGDataProviderCreateWithCFData(cfData)
let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider)
First of all, that NSData IS your PDF, no need to convert to another data type or use a library to manipulate it at the moment.
For now, simply save the NSData to your documents directory on iOS, which is not a managed persistent store like CoreData or Realm, nor is it UserDefaults. It's a folder with stuff in it.
Save to Documents Folder:
Now verify that the file is there and open it on your mac. This is to make sure you've saved an actual PDF and not anything else. This is a two step process. First find out where on earth the file went by printing the location of the documents folder from the iOS simulator:
Now copy that really long filepath and
cd [paste location]
in terminal to go there, thenopen myCoolPDF.pdf
to open it in Preview! It's magical times!Now that you have verified that you're dealing with an actual PDF it's time to display that in a WebView since it's quite simple unless you've got your own way of doing so.
Note that you still have to make it so the webview shows up, drag one onto your viewController in a storyboard and make an IBOutlet for it.
Obviously this is a quick way to make sure you get the basics going, you don't want to force unwrap unsafely using
!
.Update:
For Saving Files to Documents Directory.
For retrieving the path of Document Directory.
Here you can append your filename with backslash in front. And you can test whether your file exists there.
Starting with iOS 11 you don't need a web view and can use a dedicated PDFKit framework. With PDFKit loading a PDF from a
URL
orData
instance can be as simple as:Check out PDFKit documentation for more details.