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?

3
  • 1
    Did you try NSFileManager's setAttributes:ofItemAtPath:error:? Commented Jul 19, 2016 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") } Commented Jul 20, 2016 at 19:10
  • I'm not familiar with Swift, I think it's better if you do it. Commented Jul 20, 2016 at 23:18

1 Answer 1

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") }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.