Contents

fileExporter(isPresented:document:contentType:defaultFilename:onCompletion:)

Presents a system dialog for exporting a document that’s stored in a value type, like a structure, to a file on disk.

Declaration

nonisolated func fileExporter<D>(isPresented: Binding<Bool>, document: D?, contentType: UTType, defaultFilename: String? = nil, onCompletion: @escaping (Result<URL, any Error>) -> Void) -> some View where D : FileDocument

Parameters

  • isPresented:

    A binding to whether the dialog should be shown.

  • document:

    The in-memory document to export.

  • contentType:

    The content type to use for the exported file.

  • defaultFilename:

    If provided, the default name to use for the exported file, which the user will have an opportunity to edit prior to the export.

  • onCompletion:

    A callback that will be invoked when the operation has succeeded or failed.

    result

    A Result indicating whether the operation succeeded or failed.

Discussion

In order for the dialog to appear, both isPresented must be true and document must not be nil. When the operation is finished, isPresented will be set to false before onCompletion is called. If the user cancels the operation, isPresented will be set to false and onCompletion will not be called.

The contentType provided must be included within the document type’s writableContentTypes, otherwise the first valid writable content type will be used instead.

For example, a button that exports a text document might look like this:

struct ExportButton: View {
    @State private var isExporterPresented = false
    var document: TextFile?

    var body: some View {
        Button("Export") {
            isExporterPresented = true
        }
        .fileExporter(
            isPresented: $isExporterPresented,
            document: document,
            contentType: .utf8PlainText,
            defaultFilename: "Exported Document"
        ) { result in
            switch result {
            case .success(let url):
                print("Saved to \(url)")
            case .failure(let error):
                print(error)
            }
        }
    }
}

To further configure the dialog’s appearance and behavior, use these view modifiers: fileDialogDefaultDirectory(_:), fileDialogConfirmationLabel(_:), fileDialogMessage(_:), fileDialogBrowserOptions(_:), fileExporterFilenameLabel(_:), and fileDialogCustomizationID(_:).