How it works
FileDocumentReadConfiguration carries the information a FileDocument needs to reconstruct itself from saved data. When SwiftUI opens a document on behalf of your DocumentGroup scene, it hands your type one of these values through the throwing initializer it requires, bundling the file's contents and its resolved content type into a single argument. Reach for it whenever you adopt FileDocument: it is the structured input to init(configuration:), letting you decode bytes into your model and report a CocoaError if the file can't be read.
Accept it in the required init(configuration:)
FileDocument declares a throwing initializer that takes a single FileDocumentReadConfiguration. SwiftUI calls it whenever it loads a document, so implementing
init(configuration: FileDocumentReadConfiguration) throwsis howNoteDocumentturns a file on disk back into a live value.Read the bytes through the file property
The configuration's
fileproperty is a FileWrapper describing what was opened. For a flat file you read itsregularFileContentsto get the raw Data, as the example does withconfiguration.file.regularFileContentsbefore decoding it intotextviaString(decoding: data, as: UTF8.self).Throw when the contents can't be honored
Because init(configuration:) is throwing, you signal an unreadable or malformed file by throwing rather than returning a half-formed value. The example takes the
elsebranch and throwsCocoaError(.fileReadCorruptFile)whenregularFileContentsis nil, letting SwiftUI surface the failure to the user.Pair it with readableContentTypes
FileDocument advertises which formats it can open via
static var readableContentTypes, and SwiftUI only constructs a FileDocumentReadConfiguration for one of those types. DeclaringreadableContentTypesas[.plainText]is what lets the configuration arrive holding plain-text data your initializer is prepared to decode.
String(decoding: data, as: UTF16.self) and reopen a UTF-8 text file to watch the configuration's bytes get misread into garbled text.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct FileDocumentReadConfigurationDemo: View {
struct NoteDocument: FileDocument {
static var readableContentTypes: [UTType] { [.plainText] }
var text: String
init(text: String = "Hello") { self.text = text }
init(configuration: FileDocumentReadConfiguration) throws {
if let data = configuration.file.regularFileContents {
text = String(decoding: data, as: UTF8.self)
} else {
throw CocoaError(.fileReadCorruptFile)
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
FileWrapper(regularFileWithContents: Data(text.utf8))
}
}
@State private var doc = NoteDocument(text: "Draft note loaded from a file.")
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Label("Note.txt", systemImage: "doc.text")
.font(.headline)
Text(doc.text)
.font(.body)
.foregroundStyle(.secondary)
}
.padding()
}
}