How to show a Dialog before closing an app in SwiftUI?

When a user closes the last window, the app shall quit.
This works well with appDelegate:

import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
}
    
@main
struct buttonsApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {  // opens a window
        WindowGroup {
            ContentView()
        }
        .windowResizability(.contentSize)
    }
}

What is the proper way in SwiftUI of showing an alert that the app will quit and give the user the option to proceed or to cancel quit?

Hi!

AFAIK there is no SwiftUI-way for this. I use the old way in my app, too

final class MyWindowDelegate: NSObject, NSWindowDelegate {
    func windowShouldClose(_ sender: NSWindow) -> Bool {
        // some code
        return true
    }
}

final class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
        // some code
        return .terminateNow
    }
}

3 Likes