Cai
Cai

Reputation: 3649

Background Application: NSAlert before shutdown

I want to have a status bar application that will display a NSAlert before the system shutdown/reboot. (Just a NSStatusItem, no window.)

It detected the shutdown and show the alert, but before the user could interact with the alert, the application terminated then system turned off.

Is there a way to force the system to wait for the alert to finish before the system shutdown?

EDIT: The code did work if the application was shown in the Dock, but will not work if it's a NSApplicationActivationPolicy.Accessory or an UI Element. I tried to restored it back to the Dock before it quits but before it can pop up again it's been terminated.

Here's the code example:

func receivedPowerOffNotification(notification: NSNotification) {

        let myAlert: NSAlert = NSAlert()
        myAlert.alertStyle = NSAlertStyle.CriticalAlertStyle
        myAlert.messageText = "Title"
        myAlert.informativeText = "Please wait for this alert"
        myAlert.addButtonWithTitle("OK")
        myAlert.addButtonWithTitle("Not OK")
        let response = myAlert.runModal()
        if response != NSModalResponseOK {
            // Do something here before shutdown the system.
        }
    }
    NSApplication.sharedApplication().replyToApplicationShouldTerminate(true)
}

func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
    // userQuit = if the termination was caused by the Quit menu.
    return userQuit ? NSApplicationTerminateReply.TerminateNow : NSApplicationTerminateReply.TerminateLater
}

Upvotes: 2

Views: 577

Answers (1)

Cai
Cai

Reputation: 3649

OK, after back and forth emails with Apple's Developer Technical Support (DTS), the short answer is it's impossible (for a LSUIElement/Agent to trap a shutdown/reboot process):

Quote from an Apple Employee:

The rules change in AppKit for apps that are user-agent based. They are designed not to interact with the user, even through our documentation states you can add windows. Since your app has an NSStatusItem, which constitutes a UI, it should not be user-agent based. You are interacting with the user in this case.

I did ask if there's any "internal" ways. The answer was still no.

Upvotes: 1

Related Questions