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

萝らか妹 提交于 2020-06-26 04:25:27

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/42856370/macos-how-to-have-nssavepanel-to-add-a-file-extension-in-the-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!