Swift PDFKit How to select pdf to view from resources (PDF Selector)

166 Views Asked by At

I am working with the below code, which is displaying a pdf in my resources. However, I am trying to work out how to select a pdf name from a list which will substitute the "lipsum" resource. Currently, I am unable to pass any string variable in the place of Lipsum using navigation link. Any help would be greatly appreciated.

import SwiftUI
import UIKit
import PDFKit


struct DocView: View {
    let pdfDoc: PDFDocument

 init() {
        let url = Bundle.main.url(forResource:"Lipsum", withExtension: "pdf")!
        pdfDoc = PDFDocument(url: url)!
    }
    
    var body: some View {
        PDFKitView(showing: pdfDoc)
    }
}

struct DocView_Preview: PreviewProvider {
    static var previews: some View {
        DocView()
    }
}


struct PDFKitView: UIViewRepresentable {
    
    let pdfDocument: PDFDocument
    
    init(showing pdfDoc: PDFDocument) {
        self.pdfDocument = pdfDoc
    }
    
    //you could also have inits that take a URL or Data
    
    func makeUIView(context: Context) -> PDFView {
        let pdfView = PDFView()
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        return pdfView
    }
    
    func updateUIView(_ pdfView: PDFView, context: Context) {
        pdfView.document = pdfDocument
    }
}



I have tried passing a variable from a NavigationLink from another view containing a list, however, when I do so, it says that the pdfview does will not accept it.

1

There are 1 best solutions below

0
Ahmed Mohiy On

You can add a parameter to the initializer like this

struct DocView: View {
let pdfDoc: PDFDocument



    init(resourceName: String) {
        let url = Bundle.main.url(forResource:resourceName, withExtension: "pdf")!
        pdfDoc = PDFDocument(url: url)!
    }

    var body: some View {
       PDFKitView(showing: pdfDoc)
    }
}

and you call it from another view like this

DocView(resourceName: "pdfName")