12

Is it possible to close a macOS SwiftUI application when the last window is closed by the user, similar to the applicationShouldTerminateAfterLastWindowClosed AppDelegate function.

func applicationShouldTerminateAfterLastWindowClosed(NSApplication) -> Bool
Duncan Groenewald
  • 8,496
  • 6
  • 41
  • 76

1 Answers1

35

I found the answer here https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app

Create a class for the AppDelegate

import Foundation
import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
}

Add a property wrapper to your SwiftUI App class

import SwiftUI

@main
struct SwiftUIApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .frame(minWidth: 300, idealWidth: 300, maxWidth: .infinity, minHeight: 300, idealHeight: 300, maxHeight: .infinity)
    
        }
    }
}
Duncan Groenewald
  • 8,496
  • 6
  • 41
  • 76
  • This does not work for an application that can run both on iOS / iPadOS and macOS – Sébastien Stormacq Nov 06 '22 at 10:02
  • 1
    @SébastienStormacq - I just tested with a Multiplatform swiftUI app and the macOS version seems to work fine using this method – Duncan Groenewald Nov 06 '22 at 17:53
  • Thank you for having confirmed. I just tested on a macOS only app and I confirm it works. On my catalyst app (iOS, macOS, iPadOS), I added this entry in Info.plist to make it work (no delegate necessary) " UIApplicationSceneManifest UIApplicationSupportsMultipleScenes " – Sébastien Stormacq Nov 12 '22 at 06:42