Home > Blockchain >  Open PDF In SwiftUI
Open PDF In SwiftUI

Time:07-20

I am making PDF using TPPDF library. This makes the PDF fine and returns a URL which is like this:

pdfURL = file:///Users/taimoorarif/Library/Developer/CoreSimulator/Devices/8A2723A7-DD69-4551-A297-D30033734181/data/Containers/Data/Application/EE60FB55-13AE-4658-A829-8A85B2B6ED95/tmp/SwiftUI.pdf

If I open this URL in Google Chrome, this shows my PDF. But when I try to use

UIApplication.shared.open(pdfURL)

It did nothing.

I also made a UIViewRepresentable PDFKitView:

import SwiftUI
import PDFKit

struct PDFKitView: View {
    var url: URL
    var body: some View {
        PDFKitRepresentedView(url)
    }
}

struct PDFKitRepresentedView: UIViewRepresentable {
    let url: URL
    init(_ url: URL) {
        self.url = url
    }

    func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
        let pdfView = PDFView()
        pdfView.document = PDFDocument(url: self.url)
        pdfView.autoScales = true
        return pdfView
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
        // Update the view.
    }
}

And use it as:

PDFKitView(url: URL(string: pdfURL.absoluteString))

It also not worked.

I know this url is the path where this file is saved. So, after searching on this, I tried:

let fileURL = Bundle.main.url(forResource: pdfURL, withExtension: "pdf")!

And application is crashing here with error:

Unexpectedly found nil while unwrapping an Optional value

The question here is I want to open this PDF in my APP, whether it opens on Safari or Google Drive but don't know how to do that. So how can I open my PDF?

CodePudding user response:

Bundle.main is not FileManager. Bundle.main is for accessing your app's resources like a video, image that you added to your project using Xcode.

URL(string:) is meant for online urls. To initialize an URL for a file use URL(fileURLWithPath: anyURL.path). So what you really should do is:

PDFKitView(url: URL(fileURLWithPath: pdfURL.path))
or
PDFKitView(url: pdfURL)
  • Related