Shaul Hameed Shaul Hameed - 1 month ago 13
Swift Question

How to detect restart event in App delegate - OSX?

I want to quit the application only at the event of restart / logoff. Is there any way to find logoff/restart in OSX ?

Thanks in advance.

Answer

You can add an observer on NSWorkspace watching for NSWorkspaceWillPowerOff:

NSWorkspace.shared().notificationCenter.addObserver(self,
                                                    selector: #selector(yourMethod),
                                                    name: .NSWorkspaceWillPowerOff,
                                                    object: nil)

Here yourMethod will be called whenever the Mac is powering off (reboot or shutdown).

There's also notifications for going to sleep: NSWorkspaceWillSleep and for waking up: NSWorkspaceDidWake.