Want to pull the answer by Kyle KIM into it's own answer, as the above solution with array access caused an exception for me.
In my use case, I'm using this keyboard shortcuts library to bring the app to foreground.
I'm also using this alongside the new SwiftUI app feature, and thankfully it all works together -- this will invoke again even if you click the close button.
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow?
func applicationDidBecomeActive(_ notification: Notification) {
self.window = NSApp.mainWindow
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
KeyboardShortcuts.onKeyUp(for: .toggleApp) {
if !NSApp.isActive || !(self.window?.isKeyWindow ?? false) {
NSApp.activate(ignoringOtherApps: true)
self.window?.makeKeyAndOrderFront(self)
} else {
print("App already active")
}
}
}
}
!NSApp.isActive and the key window check are both required because when a user clicks the "close button" the widow is no longer key but still active. The app remains active until they click on a different app. You can see this happening with the focus colors of windows.
Note that this AppDelegate isn't the main entry point in my app, it's used alongside swiftUI:
@main
struct MainApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {...}
}