Showing a PDF in SwiftUI
Since iOS 11, Apple has provided PDFKit, a robust framework to display and manipulate PDF documents in your applications.
As you can imagine, PDFKit is based on UIKit; however, in this recipe, we'll see how easy it is to integrate it with SwiftUI.
Getting ready
Let's create a new SwiftUI app in Xcode called PDFReaderApp
.
We then need a PDF document to present. We are providing an example in the repo https://github.com/PacktPublishing/SwiftUI-Cookbook/blob/master/Resources/Chapter13/recipe4/PDFBook.pdf, but feel free to use a PDF document of your choice.
Copy the document in the project:
With the PDF document in the project, we are ready to implement our PDF viewer in SwiftUI.
How to do it
PDFKit provides a class called PDFView
to render a PDF document.
Because the PDFView
class is a subclass of UIView
, it must be encapsulated in a UIViewRepresentable...