I’m building a macOS app using SwiftUI with a WindowGroup(id: "rootWindow") for the main UI. The app shows a countdown timer, and the timer continues to run even after the user closes the main window (clicks the red "X"). When the timer reaches 0, I want to automatically reopen that window and bring the app to the front.
I’m currently using the following code to bring the app to the foreground and show the window when the app is still open (but not focused/resign active state):
NSApp.activate(ignoringOtherApps: true)
NSApp.windows.forEach { window in
if window.identifier?.rawValue.starts(with: "rootWindow") {
window.makeKeyAndOrderFront(nil)
}
}
However, this doesn’t work when the window has been closed. At that point, NSApp.windows no longer contains my SwiftUI window, and I have no reference to recreate or reopen it. I also cannot use openWindow environment value as it requires a view.
How can I programmatically reopen a SwiftUI WindowGroup window after it’s been closed, without requiring any user interaction (like clicking the Dock icon)?