Trying to save a .txt file not working as I would expect

79 Views Asked by At

I have a function that uses an NSSavePanel to get a URL to save a text file report. I'm trying to check to see if the resulting url ends in ".txt" and if it does, great. If it doesn't I am trying to add the ".txt" extension.

However what happens is no file is saved if the filename in the NSSavePanel dialog doesn't end in ".txt".

The result of my print statement shows that the reportURL is a URL that ends in filename with ".txt" though.

    @IBAction func saveReportButtonClicked(_ sender: NSButton) {
        guard !folders.isEmpty else { return }
        
        let savePanel = NSSavePanel()
        savePanel.canCreateDirectories = true
        savePanel.allowedContentTypes = [.text]
        savePanel.runModal()
        if let url = savePanel.url {
            var reportURL : URL!
            if url.pathExtension.uppercased() != "TXT" {
                reportURL = url.appendingPathExtension("txt")
            } else {
                reportURL = url
            }
            let data = Data("test".utf8)
            print(reportURL)
            print(reportURL.path)
            fm.createFile(atPath: reportURL.path, contents: data)
        }
    }
0

There are 0 best solutions below