Search code examples
macosswiftuiswiftui-windowgroupnswindowrestoration

How do you restrict the macOS windowing management from restoring a specific window?


I have an app that has a few windows defined as a windows group in the structure conforming to App in the main scene:

WindowGroup("StandingsView") {
    
    StandingsView()
        .environmentObject(appServices)
}
.handlesExternalEvents(matching: Set(arrayLiteral: "StandingsView"))

The appServices take some time to be configured, so I do not want to automatically restore the windows at start. I create the windows upon user selections being valid, the services being fully configured, and the user pressing a 'start' SwiftUI button:

if let standingsURL = URL(string: "raceStratLiteApp://StandingsView") {
    NSWorkspace.shared.open(standingsURL)
}

I've tried closing the windows in the appDelegate's applicationShouldTerminate(). I've also tried setting the isRestorable to false in applicationShouldTerminate:

func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
    
    for window in NSApplication.shared.windows {
        window.isRestorable = false
    }
    return .terminateNow
}

Are there any other methods to not restore a window? or better yet, to be able to programmatically restore it with its previous size, etc but launch only on user direction to 'start'

TIA


Solution

  • The code solution as @Asperi suggests in the later comment:

    func applicationDidFinishLaunching(_ notification: Notification) {
        UserDefaults.standard.register(defaults: ["NSQuitAlwaysKeepsWindows" : false])
    }