3

SwiftUI, macOS:

I'm trying to get a menu item to open "default PDF viewer of your choice", with a specific bundled PDF.

Here's what I have thus far:

import SwiftUI
import WebKit
import PDFKit


func Guide1(_ sender: Any) {
    if let pdfURL = Bundle.main.url(forResource: "Guide1", withExtension: "pdf"){
        if NSWorkspace.shared.open(pdfURL) {
    }
}
}

func Guide2(_sender: Any) {
    if let pdfURL = Bundle.main.url(forResource: "Guide2", withExtension: "pdf"){
        if NSWorkspace.shared.open(pdfURL) {
    }
}
}

Now, what I'm missing is how to call these functions.

From previous tutorials, I've found that one way of getting the menu items to "do something" is to ctrl-click and drag the Menu Item entry to First Responder, and then select functions from the list. However, these Guide1 + Guide2 functions are not displayed.

Other tutorials suggest using @IBAction - but the minute I type that into a SwiftUI app, an error tells me to get the @IBaction replaced with "nothing". So I cannot use those either.

So, are these even valid strings for opening a PDF - and if so, how do I connect a dropdown menu item so that these PDFs are opened?

esaruoho
  • 896
  • 1
  • 7
  • 25

1 Answers1

3

It needs to be added not in SwiftUI view but, for example and simplest, in AppDelegate as below

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBAction func Guide1(_ sender: Any) {
            if let pdfURL = Bundle.main.url(forResource: "Guide1", withExtension: "pdf"){
                if NSWorkspace.shared.open(pdfURL) {
            }
        }
    }

then in your Main.storyboard (or XIB) just CTRL-drag from menu item to FirstResponder and Guide1 action is there to bind (sometime build might be required before that, but as tested on Xcode 11.2 it just works).

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you! This solved it. I'm now able to make a PDF open from a Main Menu item, and it opens in, say, Preview or other things. Much appreciated. I'm going to mark this as solved :)) – esaruoho Jan 19 '20 at 08:14