Search code examples
swiftmacosappkit

How to delay quit action of quitting app in macOS?


I want play some sound just before my app get terminated by user. I can do all the customization that I want if user press quit from app menu, but if user wants quit the app from dock like this:

enter image description here

I cannot play the sound file, because I have no control on this part, how to delay or control when the real termination should be happen, when the user wants to quit the app from dock?


Solution

  • You can implement applicationShouldTerminate on your AppDelegate to tell the system what should happen when a user has requested to terminate the app.

    The possible return values are (https://developer.apple.com/documentation/appkit/nsapplication/terminatereply):

    • terminateNow
    • terminateCancel
    • terminateLater

    Note that when a user choses to quit your app, they are expecting it to quit relatively instantaneously, so you should carefully consider the UX repercussions of delaying a termination like this.