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

Time:07-04

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

CodePudding user response:

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

CodePudding user response:

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

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