Search code examples
swiftcocoansapplication

Sending replyToApplicationShouldTerminate to NSApplication in Swift


Here is my AppDelegate.swift. I implement the applicationShouldTerminate protocol from NSApplication. Which answer I give depends on the status of is.Started in the mainWindowController. (This is the SpeakLine example from Cocoa Programming for OS X: The Big Nerd Ranch Guide 5/e—I'm trying to take the example one step further and keep the program from being allowed to quit while the talking is going on.)

What I want to do is change TerminateReply.TerminateCancel to TerminateReply.TermianteLater and then send NSApplication the replyToApplicationShouldTerminate(true) signal when the talking is done. As it stands now in the MainControllerWindow.swift class I have a function set up to handle state changes in the Speech Synthesizer and that's where I want to call it.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {


    var mainWindowController: MainWindowController?

    func applicationDidFinishLaunching(aNotification: NSNotification) {

        let mainWindowController = MainWindowController()
        mainWindowController.showWindow(self)
        self.mainWindowController = mainWindowController

    }

    func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
        if (mainWindowController!.isStarted) {
            return NSApplicationTerminateReply.TerminateCancel
        } else {
        return NSApplicationTerminateReply.TerminateNow
        }
    }

}

The trouble is, when I put it here, I get an error.

   var isStarted: Bool = false {
        didSet {
            updateButtons()
            NSApplication.replyToApplicationShouldTerminate(true)
        }
    }

it tells me I can't use a bool. It also tells me I can't use an Objective C bool when I try to put YES. How do I tell NSApplication it's OK to quit now?


Solution

  • I believe you should change

    NSApplication.replyToApplicationShouldTerminate(true)
    

    to

    NSApplication.sharedApplication().replyToApplicationShouldTerminate(true)
    

    since replyToApplicationShouldTerminate is a instance method rather then a class method.