0

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)
        }
    }
psb
  • 89
  • 5
  • 2
    I guess your app sandbox is enabled – Leo Dabus Jun 30 '22 at 02:34
  • @LeoDabus yes, it is. Read/Write. I can write the test file just fine, however I have to explicitly type in the extension for it to work. It won't add the ".txt" if it wasn't typed into the NSSavePanel. – psb Jun 30 '22 at 15:01
  • 1
    Well thats why when you change the URL it doesn't work. The user has to provide the URL. If you modify the URL it is not "authorized" anymore. – Leo Dabus Jul 01 '22 at 01:24
  • 1
    Ah... I understand now. That does make sense. Thank you @LeoDabus! – psb Jul 01 '22 at 13:19

0 Answers0