5

Edit: Created a sample project illustrating the issue:

https://github.com/Harold-D/PDFView_Representable

Question:

I'm at a lost, I have this very simple UIViewRepresentable wrapper around PDFView in SwiftUI

import PDFKit
import SwiftUI

struct MyPDFView: UIViewRepresentable {
    typealias UIViewType = PDFView
    @Binding var pdf: Data

    func makeUIView(context _: UIViewRepresentableContext<MyPDFView>) -> UIViewType {
        return PDFView()
    }

    func updateUIView(_ pdfView: UIViewType, context _: UIViewRepresentableContext<MyPDFView>) {
        pdfView.document = PDFDocument(data: pdf)
    }
}

It displays the PDF correctly, but produces about 18 AttributeGraph: cycle detected through attribute messages.

@Binding var pdfStruct: PDFStruct
var body: some View {
    MyPDFView(pdf: Binding($pdfStruct.pdf)!)
}
struct PDFStruct {
    var pdf: Data?
}

How can I eliminate the retain cycle?

DIJ
  • 347
  • 4
  • 19

1 Answers1

0

I had this same issue. The way I solved it was by removing the line pdfView.document = PDFDocument(data: pdf) from the updateUIView function. I think this was causing the issue as its trying to update the document while code is still working with the document. This is how I've now done my PDFKitView

    import PDFKit
    import SwiftUI

    struct PDFKitView: UIViewRepresentable {
       typealias UIViewType = PDFView

       let pdfDocument : PDFDocument

       init(showing pdfDoc: PDFDocument){
       self.pdfDocument = pdfDoc
    }

    func makeUIView(context: 
    UIViewRepresentableContext<PDFKitView>) -> UIViewType {
        let pdfView =  PDFView()
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        return pdfView
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
    
    }
  }
SereneYeti
  • 39
  • 3