0

I have a SwiftUI app that allows only a single window. When the user tries to close the app, I want to check for some condition, show a warning and ask the user if they still want to close, and if not, then prevent it. Here's what I have so far:

class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply
    {
        //App is about to be closed
        if(some_condition())
        {
            //calls NSAlert.runModal() internally
            if(ShowMyMessageBoxToUser() == DontClose)
            {
                //Prevent app from closing
                return .terminateCancel
            }
        }

        return .terminateNow
    }
}


@main
struct MyApp: App {

    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        Window("My app title", id: "MyAppID")
        {
            ContentView()
        }
    }
}

But what happens in this case when a user clicks on the red circle on the left of my window's title bar:

enter image description here

is that the window is hidden and if the user chooses not to close the app, the applicationShouldTerminate is called over and over again.

Is there a way to catch a notification after the red close circle is clicked, but before the app window is hidden?

c00000fd
  • 20,994
  • 29
  • 177
  • 400

0 Answers0