How can I open a local PDF file using a SwiftUI button?

假如想象 提交于 2021-01-04 14:53:50

问题


I want to display a local PDF file through a new view when I tap a button. I tried doing that using a UIViewRepresentable WebView but it's not working (I have worked with WebView only through NavigationList).

I leave my code, but feel free to suggest better option if the WebView is not the most optimal.

ButtonView

import SwiftUI

struct ResumeView: View {

    let sfSymbol: String
    let text: String

    let fileUrl = Bundle.main.path(forResource: "Resume", ofType: "pdf")

    var body: some View {
        RoundedRectangle(cornerRadius: 25)
            .fill(Color.white)
            .frame(height: 50.0)
            .overlay(
                HStack {
                    Image(systemName: sfSymbol)
                        .foregroundColor(.init(red: 0.20, green: 0.33, blue: 0.55, opacity: 1.00))
                    Button(action: {
                        WebView(urlString: self.fileUrl)
                    }) {
                    Text(text)
                        .foregroundColor(.black)
                    }
            })
    }
}

WebView

import Foundation
import SwiftUI
import WebKit 

struct WebView: UIViewRepresentable {

    let urlString: String?

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) {
        if let safeUrlString = urlString {
            if let url = URL(string: safeUrlString) {
                let request = URLRequest(url: url)
                uiView.load(request)
            }
        }
    }
}

回答1:


Using PDFKit we load local PDF file. Please try below code.

import SwiftUI
struct ResumeView: View {
    ....
    let fileUrl = Bundle.main.url(forResource: "Resume", withExtension: "pdf")!
    var body: some View {
        ....
        Button(action: {
            PDFKitView(url: self.fileUrl)
        }) {
            Text(text)
                .foregroundColor(.black)
        }
        ....
    }
}

PDFKitView

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.
    }
}


来源:https://stackoverflow.com/questions/61478290/how-can-i-open-a-local-pdf-file-using-a-swiftui-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!