swiftnsalert

How to prevent NSAlert from dismiss


How can I prevent a simple NSAlert from being dismissed?

F.ex., when the application launches, I show a NSAlert with a NSTextField included. The user shall type in a password. Only if the password is correct, the user should be allowed to use the application, if not (if the password is not correct), the Alert should stay there and ask again for the password.

This is my code so far (to create the alert):

func applicationDidFinishLaunching(_ aNotification: Notification){
    let alert = NSAlert()
    alert.addButton(withTitle: "Send")
    alert.delegate = self
    alert.alertStyle = .informational
    alert.messageText = "Password - Login"
    alert.informativeText = "Please type in your password: "

    let txt = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
    txt.stringValue = "Password:"


    alert.accessoryView = txt
    alert.beginSheetModal(for: NSApplication.shared().mainWindow!) { (response) in
        if (response == NSAlertFirstButtonReturn) {
            // the alert closes here, is there any way to prevent this?
        } else {
            print("No value.")
        }
    }

OS: OS X Sierra, Swift 3


Solution

  • You can present the alert a second time; if you need to customize the behavior beyond that, you'll need to eschew NSAlert and run an NSWindow or NSPanel of your own making.