'SwiftUI: How can you make your app come to the front when clicking on the dock icon of the app?
When a SwiftUI app is minimized and the dock icon is clicked. The app won't be deminimized and put to the front just like other apps do.
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
}
}
Other delegate methods like applicationDidLaunch do get called so its not a linking issue. Does anyone know how to get this to work?
Solution 1:[1]
Use did become active callback, tested as worked with Xcode 13.3 / macOS 12.2.1
Like,
func applicationDidBecomeActive(_ notification: Notification) {
if NSApp.windows.compactMap({ $0.isVisible ? Optional(true) : nil }).isEmpty {
NSApp.windows.first?.makeKeyAndOrderFront(self)
}
}
Test module in project is here
Note: in case of active application the only application(Will/Did)Update are called in click Dock icon.
Solution 2:[2]
In delegate methods that get called when clicking on the dock icon try calling
NSApp.activate(ignoringOtherApps: true)
This should bring your app to the foreground
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Suyash Medhavi |

