Member-only story
SwiftUI Pdf View using Data/NSData
So back at WWDC in 2019 Apple released direct support for viewing PDF’s utilising their PDFKit framework including the ability to in-app customisation on how to browse them.
In this article I will go over how to display a PDF in-app utilising Swiftui but also how to share it using the new Apple sharelink API's. Also I will go over how to use NSData/Data to do that. As the API I was dealing with would return the PDF as a base64 encoded string.
Prerequisites
- Xcode 14.3
- iOS device running iOS 16 or the iOS Simulator
Showing a PDF Using Apple’s PDFKit
First thing you need to do is bring Apples PDFView functionality into SwiftUI this is done at the moment by utilising the UIViewRepresentable
Bringing PDFView into SwiftUI
I’m using Data coz I will be receiving the PDF as a stream from the API. You could use a URL as well if you wanted. I have added a simple enum that could be used to allow you to configure the PdfView with either.
import PDFKit
import SwiftUI
public enum PdfViewType {
case data(data: Data), url(url: URL)
}
struct PDFKitRepresentedView: UIViewRepresentable {
let viewingType: PdfViewType
init(_ viewingType: PdfViewType) {
self.viewingType = viewingType
}
func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) ->…