Prevent Save Panel in SwiftUI Mac app from saving as file type my app exports

I have a multiplatform SwiftUI document app project. My app has a custom document type and can export to another type. I have both types in the document’s list of writable content types.

When I save the document, the save panel on Mac has a File Format menu to save the file with an item for each writable content type. But the only type the document should save to is my custom document type. If someone chooses the exported type, they won’t be able to open the document. How do I limit the Save panel to save the document only in my custom document type?

I tried removing the exported type from the list of writable content types, but when I export the file, I get the following error message in Xcode’s console:

Attempting to export a document using a content type not included in its writableContentTypes. The first supported writable content type will be used instead.

The export works, but the file has the extension for my custom document type. Changing the file extension in the Finder makes everything work. But I don’t want people to have to manually change file extensions.

I tried taking the URL SwiftUI’s file exporter returns and changing the file extension, but I get the same error message in Xcode’s console. The exported file still has the extension for my custom document type.

I also tried adding the exported type to the list of writable content types when exporting, but the writable content types array can’t be modified at runtime.

What do I have to do to save documents only as my custom document type while exporting with the correct file extension?

  • How are you calling this code?

    If you have it via command, which calls the Save Panel, that should be a simple fix, but if you are using fileExporter, then you just need to specify the content type, which is easiest to do in the view model.

  • I don't make any explicit call in my code to open the Save panel to save the document. It's the standard SwiftUI code where choosing File > Save opens the Save panel.

    I use fileExporter to export the document. I set the content type for the file exporter to the exported file type.

Add a Comment

Replies

This question got a response in Apple's Q & A Slack

https://appledeveloper.slack.com/archives/C043025CS59/p1670878510681929

The suggestion was to limit the content types using the .fileExporter modifier.

I haven't written any code to open a Save panel when saving the document. I have the default SwiftUI behavior.

How would I use .fileExporter when someone chooses File > Save?

This is a limitation in SwiftUI. I followed the following feedback:

FB11876082