swiftmacosnssavepanel

macOS - How to have NSSavePanel to add a file extension in the file name?


I'm using this code to give the user the choice to specify a name and a location where to save a plain text file on disk. All seems to work but the saved file hasn't any extension. Actually I have not specify an extension in any part of my code, I read NSSavePanel documentation without notice the part where explained this option.

Here is the code I'm using:

    let textToExport = mainTextField.textStorage?.string

    if textToExport != "" {
        let mySave = NSSavePanel()

        mySave.begin { (result) -> Void in

            if result == NSFileHandlingPanelOKButton {
                let filename = mySave.url

                do {
                    try textToExport?.write(to: filename!, atomically: true, encoding: String.Encoding.utf8)
                } catch {
                    // failed to write file (bad permissions, bad filename etc.)
                }

            } else {
                NSBeep()
            }
        }
    }

Solution

  • Add the line

    mySave.allowedFileTypes = ["txt"]
    

    before presenting the panel.

    From the documentation:

    The value of this property specifies the file types the user can save the file as. A file type can be a common file extension, or a UTI. The default value of this property is nil, which indicates that any file type can be used. (Note that if the array is not nil and the array contains no items, an exception is raised.)

    If no extension is given by the user, the first item in the allowedFileTypes array will be used as the extension for the save panel. If the user specifies a type not in the array, and allowsOtherFileTypes is true, they will be presented with another dialog when prompted to save.