Finally solved this. The problem was that I wanted to maintain the state of the PDFKit views when switching between them (like what page you're on, how much you're zoomed in on a page, etc), so I maintain a copy of the PDFView objects after instantiating them, but I wasn't handling the makeUIView and updateUIView methods properly, which are called constantly in SwiftUI when switching between the different PDFViews, even though I wasn't unloading the views. There's not a lot of documentation about using PDFKit and SwiftUI, especially the way we're doing it with an app that needs to open multiple PDFs and display them in tabs, and even display two of them side-by-side at the same time.
Here is what my core SwiftUI wrapper around PDFKit now looks like:
import PDFKit
import SwiftUI
struct PDFViewSwiftUIWrapper: UIViewRepresentable {
var myViewerModel: PDFViewerModel
func makeUIView(context: Context) -> PDFView {
return myViewerModel.myPDFView
}
func updateUIView(_ pdfView: PDFView, context: Context) {
pdfView.document = myViewerModel.myPDFView.document
}
}
It's super-basic, but both functions need to do something; I thought "updateUIView" would only be called if you were displaying a different PDF in the same viewer, but it gets called every time the view displays.
The PDFViewerModel is the class that I instantiate and hold on to. I have one of these for each PDF tab that is opened in the app. By keeping a copy of this, which has the PDFView in it, I can maintain the state of PDFView, like the zoom level, the page #, etc:
// I have to set this as Indentifiable so I can use it with ForEach
class PDFViewerModel: ObservableObject, Identifiable {
var myPDFView = PDFView()
// There are other properties like these so we can have additional state for the viewer, like a word search textbox. This isn't part of PDFView; you have to add these UI features.
var showBookmarkPopover = false
var showSearchToolbar = false
...
}
When you click to open another PDF in a new tab, it instantiates it and adds it to the array like this:
let pdfViewerModel = PDFViewerModel()
if let unwrappedPdfDoc = PDFDocument(url: getMyURL()) {
pdfViewerModel.myPDFView.document = unwrappedPdfDoc
}
currentTabs.append(pdfViewerModel)
There's a SwiftUI view that displays the PDFViewSwiftUIWrapper and some other helper controls, like the search toolbar, and each of these is displayed like this:
ForEach(currentTabs) { pdfViewerModel in
PDFViewer(pdfViewerModel: pdfViewerModel)
}
This problem was a hybrid of the way SwiftUI gets called repeatedly, which I didn't realize, even if the state hadn't necessarily changed, along with the correct way to integrate PDFKit into SwiftUI. Hope this helps anyone with a similar issue!