To run some code before app termination in a macOS app using SwiftUI, the correct approach would involve placing the termination logic within a view, such as the ContentView. Here’s how you can do it:
Handling App Termination in a SwiftUI View
-
Add a View Modifier in
ContentViewor Any Root View: You can use.onReceivewithin your main view to listen for the termination notification. -
Integrate Termination Logic into the Root View: The root view is the entry point of your app, where you can attach this logic.
Example Code:
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in
// This code will be executed just before the app terminates
performCleanupBeforeExit()
}
}
}
func performCleanupBeforeExit() {
// Perform any necessary cleanup before the app exits
print("Performing cleanup before app termination.")
// Insert your termination cleanup logic here
}
}
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.padding()
}
}
Explanation:
-
WindowGroup: TheWindowGroupis used to define the main scene of your macOS application. It contains your root view,ContentViewin this case. -
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)): This modifier is now attached toContentView, which is the root view inside theWindowGroup. It listens for theNSApplication.willTerminateNotification, ensuring that your cleanup code runs just before the app terminates. -
performCleanupBeforeExit(): This function contains the cleanup logic that you want to execute when the app is about to be terminated. This function is called within the.onReceivemodifier.
Why This Works:
Attaching .onReceive to ContentView ensures that your app can respond to termination events correctly. Since ContentView is the main view within your WindowGroup, it will remain active for the duration of the app’s lifecycle, making it a suitable place to handle the termination event.