Search code examples
xcodemacosswiftuinsmenuitem

macOS SwiftUI: MenuItem to open default browser to a URL?


I've been trying to make a MenuItem in my macOS SwiftUI app to open a default browser to a specific URL.

Since I already had a MenuItem open up a PDF, I tried to modify this:

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

Into this:

    @IBAction func Google(_ sender: NSMenuItem) {
        if let fileURL = Bundle.main.url(forResource: "http://google.fi") {
                NSWorkspace.shared.open(fileURL as URL)
        }
    }

But kept being told that forResource should be replaced with forAuxiliaryExecutable. I make that change, and the code still does nothing.

I've mapped, of course the MenuItem Google to First Responder and then to the specific IBAction, but..

What am I missing?


Solution

  • It should be as follows

    @IBAction func Google(_ sender: NSMenuItem) {
        if let url = URL(string: "http://google.fi") {
            NSWorkspace.shared.open(url)
        }
    }