Home > other >  Prevent or clear app state persistence for MacOS SwiftUI Document Based App
Prevent or clear app state persistence for MacOS SwiftUI Document Based App

Time:11-27

I am developing a MacOS Document based app using SwitfUI on MacOS 12.0.1 using Xcode 13.1 on a MacbookPro M1 Pro. I am encountering an issue that the app is always re-opening the document browser at the last used directory. Which is OK when it is on the Machine but a pain if the last used was on a network drive. I am trying to find a way of suppressing this "always restore using the last directory" mode of operation.

I have tried using the @NSApplicationDelegateAdaptor approach and implementing;

  func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
    print(#function   " returning false")
    return false
  }

within my NSApplicationDelegate class, which does get called (although it seems sometimes after the dialog is presented), however this does not stop the app secretly remembering the last directory.

Does any know where this information might be being hidden or if it can be suppressed ?

I have looked for, but cannot find, a way of injecting a starting directory into a DocumentGroup as a possible solution.

TIA Alan.

CodePudding user response:

Ok, for anyone who ends up here looking for a similar issue.

After a chunk of digging I found the answer, for me, was to add

    UserDefaults.standard.removeObject(forKey: "NSNavLastRootDirectory")

into the app startup. It was also suggested to do

UserDefaults.standard.removeObject(forKey: "NSNavLastCurrentDirectory")

However, just doing the first appears to suppress the file open dialog, doing both causes the file open dialog to open with the user Documents directory.

  • Related