Disables multiple windows in MacOS with SwiftUI

Recently, I have crated a new MacOS app using SwiftUI. I want the app to be single window app, so I want to disable multiple windows in MacOS. Here is how I did it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@main
struct GitStarApp: App {
@Environment(\.scenePhase) var scenePhase
@State private var url: URL?

var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
print("open from link: \(url)")
}
.handlesExternalEvents(preferring: Set(arrayLiteral: "*"), allowing: Set(arrayLiteral: "*"))
.onAppear(perform: {
NSWindow.allowsAutomaticWindowTabbing = false
})
}
.commands(content: {
CommandGroup(replacing: .newItem) { }
})
}
}

There are three ways that can open a new window for a MacOS app, we should disable all of them.

Keyboard shortcut Command+N will invoke the newItem command and open a new window. So we need using commands modifier to replace the newItem command with an empty one to disable the keyboard shortcut.

The app’s view menu can open the tool bar showed in the main window. There is a add button in the right of the tool bar, which can open a new window. We need to disable the tool bar to disable users click the add button.

1
NSWindow.allowsAutomaticWindowTabbing = false

My app has a URLScheme for getting authorization code from the browser. When the app is not running, the system will open a new window to handle the URLScheme.
But we don’t want the app to reopen a new window when there already has existed a window. So we need to disable the URLScheme to open multiple windows.
handlesExternalEvents(preferring: Set(arrayLiteral: "*"), allowing: Set(arrayLiteral: "*")) will handle all URLScheme events and open the URL in the existing window.