macosswiftuidocument

How to handle different document types in a document based macOS app?


How do I handle two different custom document types in one macOS document app?

Starting from the macOS Document App template I define two types, which are also registered in the info.plist :

extension UTType {
    static var test1: UTType {
        UTType(exportedAs: "com.exapmple.test1")
    }
}

extension UTType {
    static var test2: UTType {
        UTType(exportedAs: "com.example.test2")
    }
}

Apple documentation says:

Your app can support multiple document types by adding additional document group scenes:

But the shown example has only one type that can be created, the other is read only (Editor mode).

If I do this in the main app struct (which is basically boilerplate from the template:

@main
struct MultipleDocumentsApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: DocumentOne()) { file in
            Content1View(document: file.$document)
        }
        DocumentGroup(newDocument: DocumentTwo()) { file in
            Content2View(document: file.$document)
        }
    }
}

..the resulting New menu looks like this, and I can only create documents of type 1:

enter image description here

Obviously I would need two different New... menu items for the two doc types. Any ideas how I can achieve this?


Solution

  • It is still NSDocumentController based, so pros&cons are also the same - we have automatic handling for default document type, for everything else - back to coding.

    So all you've done is correct, the only left is to add, programmatically, creation of new document of other (non default) type.

    Here is main part of approach:

    Button("New Document2") {
      let dc = NSDocumentController.shared
      if let newDocument = try? dc.makeUntitledDocument(ofType: "com.example2.plain-text") {
        dc.addDocument(newDocument)
        newDocument.makeWindowControllers()
        newDocument.showWindows()
      }
    }
    

    Complete findings and code is here