macosnsalert

How to place a question mark button in a NSAlert that opens an online web page?


EDIT: My question was not very clear now I edited it to make it clear that I need to open an online web page and not the help book.

I would like to include a question mark button in a NSAlert in a macOS project that points to an online web page with the help resource.

I saw here that there are two possibilities:

var showsHelp: Bool Specifies whether the alert has a help button.

var helpAnchor: String? The alert’s HTML help anchor.

But I can't figure out how to implement it.

I use this code:

@IBAction func buttonPressed(_ sender: Any) {
    let myAlert: NSAlert = NSAlert()

    myAlert.messageText = "Message"
    myAlert.informativeText = "Informative text."

    myAlert.showsSuppressionButton = true

    myAlert.addButton(withTitle: "Later")
    myAlert.addButton(withTitle: "Now")
    myAlert.addButton(withTitle: "OK")

    let choice = myAlert.runModal()

    switch choice {
    case NSAlertFirstButtonReturn:
        print ("OK")
    case NSAlertSecondButtonReturn:
        print ("Now")
    case NSAlertThirdButtonReturn:
        print ("Later")
    default: break

    }
    if myAlert.suppressionButton!.state == 1 {
        print ("Checked")
    } else {
        print ("Not checked")
    }

}

Solution

  • You should make your controller class conform to NSAlertDelegate.
    Then, set myAlert.delegate = self and myAlert.showsHelp = true.
    In your controller class, implement func alertShowHelp(_ alert: NSAlert) -> Bool to do whatever you like.

    In general, to open URLs in the user's default browser, use NSWorkspace and its open() method.