4

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

marc-medley
  • 8,931
  • 5
  • 60
  • 66
Scott
  • 1,034
  • 1
  • 9
  • 19
  • If you mean disable for always then just put into UserDefaults false for NSQuitAlwaysKeepsWindows key. – Asperi Jul 04 '22 at 04:38
  • Thanks @Asperi. So its not a code change but an environment change that can be done by the installer. I'll provide an answer based on your tip – Scott Jul 04 '22 at 05:12
  • No, it is possible to set in code, e.g. in app delegate on did finish launching via `UserDefaults.register(defaults:...` – Asperi Jul 04 '22 at 05:15

2 Answers2

4

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

func applicationDidFinishLaunching(_ notification: Notification) {
    UserDefaults.standard.register(defaults: ["NSQuitAlwaysKeepsWindows" : false])
}
marc-medley
  • 8,931
  • 5
  • 60
  • 66
Scott
  • 1,034
  • 1
  • 9
  • 19
0

From the tip provide by @Asperi, writing the following to defaults will cease the writing of the window states:

$ defaults write <bundleid> NSQuitAlwaysKeepsWindows -bool false

So this is not a code change to the app, but rather an environment config the would be done on install.

I also deleted the savedState directory located at ~/Library/Saved Application State/<bundleid>.savedState for archive builds and at ~/Library/Containers/<App Name>/Data/Library/Saved Application State/<bundleid>.savedState for debug builds. Am not sure if that mattered but once doing these steps it solved the problem. Thanks @Asperi

Scott
  • 1,034
  • 1
  • 9
  • 19