I try to use the SwiftUI fileExporter
modifier to save different kinds of documents from my app on macOS. Therefore, I store the document to save in an optional FileDocument?
property.
import SwiftUI
import UniformTypeIdentifiers
struct PlaintextFile: FileDocument {
static var readableContentTypes = [UTType.plainText]
var text: String = ""
init(text: String) {
self.text = text
}
init(configuration: ReadConfiguration) throws {
if let data = configuration.file.regularFileContents {
text = String(decoding: data, as: UTF8.self)
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = Data(text.utf8)
return FileWrapper(regularFileWithContents: data)
}
}
struct ContentView: View {
@State private var showFileExporter = false
private let document: FileDocument? = PlaintextFile(text: "")
var body: some View {
Button("Save File: ") {
self.showFileExporter = true
}
.padding()
.fileExporter(isPresented: self.$showFileExporter, document: self.document, contentType: .plainText) { _ in }
}
}
However, this sample code above does not compile unless I initialize PlaintextFile
directly in the fileExporter
call. With the sample code the compiler shows the error
ContentView.swift:37:10: No exact matches in call to instance method 'fileExporter'
/SwiftUI.View:5:17: Candidate requires that 'FileDocument' conform to 'FileDocument' (requirement specified as 'D' == 'FileDocument')
Is there a way to not specify the document to save directly in the modifier but maintain it as optional property?