0

I'm saving some objects to a file using Key Value Coding. I'd like the extension of the saved file to be hidden (or at least be hidden unless the value in Finder → Preferences → Advanced "Show All File Extensions" is true), but I can't seem to get it working.

I'm saving the file like so:

let saveDialog  = NSSavePanel()
        saveDialog.allowedFileTypes = ["purr"]

        saveDialog.beginWithCompletionHandler() { (result: Int) -> Void in
            if result == NSFileHandlingPanelOKButton {


                NSFileManager.defaultManager()
                    .createFileAtPath(saveDialog.URL!.path!, contents: NSData(), attributes: [NSFileExtensionHidden: NSNumber(bool: true)])
                let _ = NSKeyedArchiver.archiveRootObject(safePhrases, toFile: saveDialog.URL!.path!)
            }
        }

        return saveDialog.URL

But when viewing the saved files in Finder, the extension is always visible. How can I resolve this?

glenstorey
  • 5,134
  • 5
  • 39
  • 71
  • 1
    Did you try `NSFileManager`'s `setAttributes:ofItemAtPath:error:`? – Willeke Jul 19 '16 at 22:27
  • That worked! Do you want to write up an answer or shall I? Thankyou! `do { try NSFileManager.defaultManager().setAttributes([NSFileExtensionHidden: NSNumber(bool: true)], ofItemAtPath: saveDialog.URL!.path!) } catch _{ Swift.print("Unable to hide extension") }` – glenstorey Jul 20 '16 at 19:10
  • I'm not familiar with Swift, I think it's better if you do it. – Willeke Jul 20 '16 at 23:18

1 Answers1

2

After Willeke suggestion I set the attributes after writing the file, using NSFileManager's setAttributes:ofItemAtPath:error.

do { try NSFileManager.defaultManager().setAttributes
    ([NSFileExtensionHidden: NSNumber(bool: true)], ofItemAtPath: saveDialog.URL!.path!) } 

catch _{ Swift.print("Unable to hide extension") }
glenstorey
  • 5,134
  • 5
  • 39
  • 71