Restoring document window position in macOS

Hi all,


In a macOS document based app, I'm using this code to open all the documents contained in a folder inside Application Support.


The code works fine but the open documents are not maintaining the position they had when closed.


    [....]
            for file in myFileNames {
                let fileName = "\(file).docuExperiments"
                let directoryURL = appSupportURL.appendingPathComponent(bundleIdentifier).appendingPathComponent("Documents")
                let docURL = URL(string: fileName, relativeTo:directoryURL)
      
                let documentController = NSDocumentController.shared()
                documentController.openDocument(withContentsOf: docURL!, display: true) {
                    // completionHandler (NSDocument?, Bool, Error?)
                    (document, documentWasAlreadyOpen, error) in
                    if error != nil
                    { print("An error occured")
                    }
                }
            }
          
    [....]


And


        override func windowDidLoad() {
          super.windowDidLoad()
            self.windowFrameAutosaveName = "position"
            // this seems to affect only the first automatically created document window
        }


Can you help me to improve the code?


PS

Somebody knows also if there also is the possibility to open all the documents in a unique tabbed window?

Accepted Answer

If you use the same window frame autosave name for all windows, then it's shared across all documents, so multiple documents cascade. You could use a unique autosave name for each document, which means you'd have to store the name in each document.

Thank you so much, which is the best way in your opinion, to store the name in each document to then retrive it in windowDidLoad?

There's no magic solution. If you control the format of your document files, you can arrange to store the autosave name in the file. If the file has a standard format, you might still be able to make that work. For example, if your documents are text files, you can store something on the first line of the text file. Your document subclass has a reading and a writing/saving method that provides the actual data that's written to the file, and these methods can strip off or add additional information.


Or you can use a second file with the same name as the document file but a different extension.


Or you can use a subdirectory for each document, containing the actual document file and other file(s).


Or you can keep an "index" document in your App Support subfolder, which lists known documents and the extra information.


Etc.

Thank you for the info!

Restoring document window position in macOS
 
 
Q