How can an app be deminimized when clicking on its app icon in a full SwiftUI app?

When a macOS SwiftUI app is minimized and the dock icon is clicked. The app won't be deminimized and put to the front just like other native apps do.

/*
macOS Monterey: 12.3.1 (21E258)
Xcode: 13.3.1 (13E500a)
Swift: 5
*/

import SwiftUI

@main
struct MyApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            MainView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        // THIS IS NEVER CALLED!!!
        if !flag {
            for window: AnyObject in sender.windows {
                window.makeKeyAndOrderFront(self)
            }
        }
        
        return true
    }
}


Replies

Appearantly no Apple engineer or community member knew the answer. I finally found a work-around and I am happy to share it with the people also struggling with the same issue which still exists in the latest Xcode Beta.

import SwiftUI

@main
struct YourApp: App {
  @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
   
  var body: some Scene {
    WindowGroup {
      MainView()
    }
  }
}

class AppDelegate: NSObject, NSApplicationDelegate {   
  func applicationDidBecomeActive(_ notification: Notification) {
    if let window = NSApp.windows.first {
      window.deminiaturize(nil)
    }
  }
   
  func applicationDidChangeOcclusionState(_ notification: Notification) {
    if let window = NSApp.windows.first, window.isMiniaturized {
      NSWorkspace.shared.runningApplications.first(where: {
        $0.activationPolicy == .regular
      })?.activate(options: .activateAllWindows)
    }
  }
}