David DelMonte David DelMonte - 1 year ago 80
Swift Question

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

Please tell me what I'm doing wrong.


Answer Source

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

override func viewDidAppear() {