beeb beeb - 10 days ago 6
Swift Question

Re-open Finder windows after programmatic termination

I am developing a utility that needs to restart the Finder in order for changes to appear.

I use

NSRunningApplication
's
terminate
function to ensure no copy operation is happening, etc (swift):

let apps = NSRunningApplication.runningApplicationsWithBundleIdentifier("com.apple.finder")
if apps.count > 0 {
let finder = apps[0]
finder.terminate()
}


Since I am listening for
NSWorkspaceDidTerminateApplicationNotification
in the
sharedWorkspace.notificationCenter
, I can then launch Finder again with
launchAppWithBundleIdentifier
. All of this works totally fine.

Now, when the Finder starts again, the windows that were previously open have been closed. I would like to re-open them, regardless of the user's preferences for "Restore windows when quitting and re-opening apps".

This is because the Finder restart is a side effect of my software's activity and the user most definitely didn't intend to close the windows.

I could maybe see this happening with AppleScript but I am not experienced enough to devise a way to get all windows state (including window placement and size), store them during the Finder restart, and re-open them afterwards.

Any help would be greatly appreciated!

Answer

Funny thing, I actually found the answer somewhere I didn't expect: the Finder defaults. As it happens (source), there is a hidden preference named NSQuitAlwaysKeepsWindows that allows to restore Finder windows after a restart.

if let finderDefaults = NSUserDefaults(suiteName: "com.apple.finder") {
    finderDefaults.setBool(true, forKey: "NSQuitAlwaysKeepsWindows")
}