Home > Back-end >  In my Mac app, how can I open a local PDF file using a SwiftUI button?
In my Mac app, how can I open a local PDF file using a SwiftUI button?

Time:03-17

In my Mac app, I want to display a local PDF file through a new view when I tap a button. The StackOverflow post (here) shows how to do it for an iOS app using UIViewRepresentable, but this does not work for a Mac app.

CodePudding user response:

macOS 11, iOS 14

There is a native SwiftUI view modifier for the QuickLook preview since macOS 11 / iOS 14. You can set the binding to the URL to your PDF File (or any other type that can be shown in QuickLook). Then the system presents the file. If the binding value is nil, the preview will not show or will be dismissed if currently shown.

.quickLookPreview(_ item: Binding<URL?>)

CodePudding user response:

This answer is just to add more information to mw_906's answer above. I created a file called UserGuide.pdf and placed it into my app's bundle. The syntax of my ContentView file is

import SwiftUI
import QuickLook

struct ContentView: View {
    @State var userGuideUrl: URL?
        Button(action: {
            userGuideUrl = Bundle.main.url(forResource: "UserGuide", withExtension: "pdf")
        } ) {
            Text("UserGuide")
        }
        .help("This button displays the User Guide.")
        .quickLookPreview($userGuideUrl)
    }
}

Now that Apple has provided such a simple way of displaying files, I encourage all Apple developers to use it to include User Guides and other helpful documentation for their apps.

  • Related