MacOS SwiftUI access modelContext from menu (.commands)?

Adding an Import... menu item using .commands{CommandGroup... on

DocumentGroup(
...
    ) {
      ContentView()
    }
   .commands {
      CommandGroup(replacing: .importExport) {
        Button("Import…") {
          isImporting = true
        }
        .keyboardShortcut("I", modifiers: .option)
        .fileImporter(
          isPresented: $isImporting,
          allowedContentTypes: [.commaSeparatedText],
          allowsMultipleSelection: false
        ) { result in
          switch result {
            case .success(let urls):
              print("File import success")
              ImportCSV.importCSV(url: urls, in: context) // This is the issue
            case .failure(let error):
              print("File import error: \(error)")
          }
        }
      }

I could get this to work if I were not using DocumentGroup but instead programmatically creating the modelContext.

  1. using the shared modelContext in ImportCSV is not possible since that is not a View
  2. passing the context as shown above would work if I knew how to get the modelContext but does it even exist yet in Main?
  3. Is this the right place to put the commands code?
  4. Perhaps the best thing is to have a view appear on import, then used the shared modelContext. In Xcode menu File/Add Package Dependencies... opens a popup. How is that done?
Answered by pikes in 815274022

I added a .sheet in Main where I can access the shared modelContext and all is well. I'd still appreciate answers to #3

Accepted Answer

I added a .sheet in Main where I can access the shared modelContext and all is well. I'd still appreciate answers to #3

MacOS SwiftUI access modelContext from menu (.commands)?
 
 
Q