SwiftUI UIViewRepresentable PDFKit PDFView AttributeGraph: cycle detected through attribute
Asked Answered
S

1

6

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?

Seafood answered 16/10, 2021 at 21:23 Comment(4)
Did you ever fix this? Im having the same issueVillada
Nope, unfortunately not. But now while typing this reply I wonder if it occurs on a real device as well, only tested it on the simulator.Seafood
I'm experiencing this too, and it does occur on a real device, not just on the simulator.Humanism
Also having this, any help is welcome!Inhospitable
M
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) {
    
    }
  }
Moyers answered 31/3, 2023 at 14:34 Comment(2)
the spacing is a bit weird in my code blockMoyers
If I remove that codeblock, the .pdf-file isn't displayed anymorePilewort

© 2022 - 2024 — McMap. All rights reserved.