How to terminate the SwiftUI app when the window is closed

This article explains how to terminate the SwiftUI app when the window is closed.

TOC

With the WindowGroup

If you specify the SwiftUI to the “Interface” of project option when you creating the project, the generated code will be following.

import SwiftUI

@main
struct TerminateOnCloseApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

The root view of the window created by this code is ContentView. When a window is closed is when the ContentView is hidden, so you can use the .onDisappear modifier to terminate the application when the window is closed with the following code.

import SwiftUI

@main
struct TerminateOnCloseApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onDisappear {
                    terminateApp()
                }
        }
    }
    
    private func terminateApp() {
        NSApplication.shared.terminate(self)
    }
}

How to terminate the app

Use NSApplication.terminate() method to terminate the application. Get the shared instance with shared same as like the sample code, and you can terminate the app with the terminate() method.

Let's share this post !

Author of this article

Akira Hayashiのアバター Akira Hayashi Representative, Software Engineer

I am an application developer loves programming. This blog is a tech blog, its articles are learning notes. In my work, I mainly focus on desktop and mobile application development, but I also write technical books and teach seminars. The websites of my work and books are here -> RK Kaihatsu.

TOC