Handling application force quit in Swift for macOS applications

152 views Asked by At

"I'm currently developing a macOS application using Swift and I need to perform a certain action (in my case, remapping a key) when the application is terminated. I am able to handle the situation where the application is quit normally using the applicationWillTerminate(_:) method in the AppDelegate, but this doesn't get called when the application is force quit, such as through the Activity Monitor.

I understand that when an application is forcibly quit, the operating system sends it a SIGKILL signal that it cannot ignore or handle, so it immediately stops without executing any further code. However, is there any workaround or alternative approach that would allow me to handle this scenario or achieve a similar effect? I would appreciate any suggestions or insights."

1

There are 1 answers

0
Rob Napier On

You can run a separate process that monitors the first, and detects when it stops running. During normal shutdown, the main program can terminate the monitor. This can also be circular, so that the main program watches the monitor and relaunches it if the monitor is killed. Or you can use a Launch Daemon to automatically re-launch the monitor if needed.