Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write an NSAlert in latest swift?

I'm trying to write this alert:

func alertUser() {
        let alert = NSAlert()
        alert.messageText = "message 1"
        alert.informativeText = "info1"
        alert.informativeText = "info2"
        alert.addButton(withTitle: "NO")
        alert.addButton(withTitle: "YES")
        alert.beginSheetModal(for: self.view.window!) { (returnCode: NSModalResponse) -> Void in
            print ("returnCode: ", returnCode)
        }

but I get the dreaded unexpectedly found nil while unwrapping an Optional value message on the line alert.beginSheetModal

Please tell me what I'm doing wrong.

Thanks

like image 531
ICL1901 Avatar asked Sep 10 '16 14:09

ICL1901


1 Answers

You should run your code from viewDidAppear because your view controller has not created a window object in viewDidLoad.

override func viewDidAppear() {
    super.viewDidAppear()

    alertUser()
}
like image 116
Michael Samoylov Avatar answered Sep 28 '22 20:09

Michael Samoylov