swiftcocoansfilemanagerkey-value-codingnssavepanel

Save file but hide file extension - Cocoa with Key Value Coding


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?


Solution

  • 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") }