SwiftUI apps on macOS don't relaunch after being minimized

I've been working on a macOS app using pure SwiftUI, and I've found a strange behavior that I've no idea how to solve. If you have enabled the System Preferences > Dock & Menu Bar > Minimize windows into application icon flag, when you minimize the window it never launches again when clicking the app icon on the dock. This does not happen with an AppKit application.

The issue can be seen here (video + 2 sample projects): https://github.com/xmollv/macOSMinimizeIssueOnSwiftUI

Literally they're empty apps, just created them using Xcode's assistant (the SwiftUI one has the steps to repro the issue in the UI). The only solution that I found to launch the SwiftUI one is rick clicking the app icon, and then selecting the window, but of course nobody expects that.

My question is: is there any way launch a minimized SwiftUI app when clicking the dock icon?

Answered by xmollv in 715063022

I've found a hack since AppDelegate.applicationShouldHandleReopen(_:hasVisibleWindows:) is not called as explained in the comment above. Apparently AppDelegate.applicationWillBecomeActive(_:) is called when you click on the Dock app icon if the window is miniaturized, so inside that method simply add this and seems to be working as expected (macOS 12.4):

func applicationWillBecomeActive(_ notification: Notification) {
    (notification.object as? NSApplication)?.windows.first?.makeKeyAndOrderFront(self)
}

I've been digging how to implement this manually and seems that AppDelegate.applicationShouldHandleReopen(_:hasVisibleWindows:) would've done the trick, but even if you implement the @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate, that method is never called. Found another example of the same issue online: https://www.reddit.com/r/SwiftUI/comments/u5srtt/applicationshouldhandlereopen_is_not_called_in

Accepted Answer

I've found a hack since AppDelegate.applicationShouldHandleReopen(_:hasVisibleWindows:) is not called as explained in the comment above. Apparently AppDelegate.applicationWillBecomeActive(_:) is called when you click on the Dock app icon if the window is miniaturized, so inside that method simply add this and seems to be working as expected (macOS 12.4):

func applicationWillBecomeActive(_ notification: Notification) {
    (notification.object as? NSApplication)?.windows.first?.makeKeyAndOrderFront(self)
}

I had the same problem. Found a solution, just set AppDelegate on launch.

func applicationDidFinishLaunching(_ aNotification: Notification) {
        NSApplication.shared.delegate = self
}

func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
         //Now is working
        return true
}
SwiftUI apps on macOS don't relaunch after being minimized
 
 
Q