swiftcocoainfo.plistnsdocumentnssavepanel

NSDocument-Based Application: Selecting Default File Type in NSSavePanel


enter image description here

I'm playing with the NSDocument class to make a simple document-based application. My info.plist contains four document content type identifiers including public.text, public.plain-text, public.source-cde, public.rtf as shown above. And I get those file types listed if I involke the save-panel (NSSavePanel) as shown below.

enter image description here

My question is whether or not it is possible to select one of the file types programmatically. Can I select 'rich text (RTF)' when the save panel appears?

The following is part of my document (NSDocument) file.

import Cocoa

class Document: NSDocument {
    override init() {
        super.init()
    }

    override class var autosavesInPlace: Bool {
        return false
    }
    
    override func save(withDelegate delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
        if let _ = fileURL {
            Swift.print("Saved!!!")
        } else {
            Swift.print("Not saved yet...")
            NSApp.sendAction(#selector(NSDocument.saveAs(_:)), to: nil, from: self)
        }
    }
    
    override func writableTypes(for saveOperation: NSDocument.SaveOperationType) -> [String] {
        return super.writableTypes(for: saveOperation)
    }
    
    override func prepareSavePanel(_ savePanel: NSSavePanel) -> Bool {
        savePanel.allowsOtherFileTypes = true
        savePanel.isExtensionHidden = false
        
        guard let accessoryView = savePanel.accessoryView else { return true }
        for sub in accessoryView.subviews {
            Swift.print("Class: \(sub.className)")
            /*
            if sub.isKind(of: NSPopUpButton.self) {
                if let popUpButton = sub as? NSPopUpButton {
                    popUpButton.selectItem(at: 5)
                    Swift.print("Sure")
                }
            }
            */
            
        }
        return true
    }
}

I see this topic as a similar title where he uses IKSaveOptions, which is used 'for saving image data' according to the doc. My application deals with text.

Thanks.


Solution

  • The default file format is fileType. Set fileType in writableTypes(for:) or runModalSavePanel(for:delegate:didSave:contextInfo:).

    override func writableTypes(for saveOperation: NSDocument.SaveOperationType) -> [String] {
        fileType = "public.rtf"
        return super.writableTypes(for: saveOperation)
    }