macOS - 如何让 NSSavePanel 在文件名中添加文件扩展名?

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

我使用此代码让用户可以选择指定名称和在磁盘上保存纯文本文件的位置。一切似乎都有效,但保存的文件没有任何扩展名。实际上我没有在代码的任何部分指定扩展名,我阅读了 NSSavePanel 文档而没有注意到解释此选项的部分。

这是我使用的代码:

    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()
            }
        }
    }

添加行

mySave.allowedFileTypes = ["txt"]

在展示面板之前。

来自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.