7

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

ICL1901
  • 7,632
  • 14
  • 90
  • 138

1 Answers1

4

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()
}
Michael Samoylov
  • 2,933
  • 3
  • 25
  • 33