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

Suppose you specify the SwiftUI to the “Interface” of the project option when you create the project. In that case, 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. The time when a window is closed, it is 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. To do so, get the shared instance with the shared property, like the sample code, and you can terminate the app with the terminate() method.

Authored Books

Let's share this post !

Author of this article

Akira Hayashi (林 晃)のアバター Akira Hayashi (林 晃) Representative(代表), Software Engineer(ソフトウェアエンジニア)

アールケー開発代表。Appleプラットフォーム向けの開発を専門としているソフトウェアエンジニア。ソフトウェアの受託開発、技術書執筆、技術指導・セミナー講師。note, Medium, LinkedIn
-
Representative of RK Kaihatsu. Software Engineer Specializing in Development for the Apple Platform. Specializing in contract software development, technical writing, and serving as a tech workshop lecturer. note, Medium, LinkedIn

TOC