Shutdown event in macOS

I wanted to identify the shutdown event in macOS, so that If my application is running and the user performs a system shutdown then my application could be notified of the shutdown event and perform finalization.

I came across NSWorkspaceWillPowerOffNotification which is exactly what I require, however, I created a sample application to observe for this notification. Is is observed that right before the system shuts down, the OS terminates my application invoking applicationWillTerminate(_:) delegate and the observer method for 'NSWorkspaceWillPowerOffNotification' is not invoked.

I could perform my finalization in the applicationWillTerminate, but I wanted to know why is the observer not getting invoked. Also why is NSWorkspaceWillPowerOffNotification, even provided by apple when it invoked the termination delegate before shutdown?

below is how I m adding the observer:

NotificationCenter.default.addObserver(forName: NSWorkspace.willPowerOffNotification, object: nil, queue: nil, using: AppDelegate.handlePowerOffNotification)

Below is my observer function, which just logs:

   public static func handlePowerOffNotification(_ notification: Notification) {
       
         NSLog (AppDelegate.TAG + "System will power off soon! Perform any necessary cleanup tasks.")
         
// custom logger to log to a file
         TWLog.Log ("System will power off soon! Perform any necessary cleanup tasks.")
     }
        
Answered by DTS Engineer in 787399022

That’s because it’s an instance property. Try NSWorkspace.shared.notificationCenter.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The documentation of NSWorkspaceWillPowerOffNotification says

To receive this notification, use notificationCenter to register for it. If you use a different notification center to register, you won’t receive the notification.

That is, when you add the observer, you need to use NSWorkspace.notificationCenter instead of NotificationCenter.default.

@JWWalker NSWorkspace.notificationCenter seems to be no longer supported. It is giving the above error.

Accepted Answer

That’s because it’s an instance property. Try NSWorkspace.shared.notificationCenter.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Shutdown event in macOS
 
 
Q