ReadableDocument
A document type that supports reading from file.
Declaration
protocol ReadableDocument : AnyObjectOverview
Conform to ReadableDocument to build a read-only document viewer, or combine with WritableDocument (via the Document protocol) for full read-write support.
A readable document is a reference type so that SwiftUI can maintain a stable identity across updates. Use @Observable to enable per-property change tracking:
@Observable
final class MarkdownViewer: ReadableDocument {
static let readableContentTypes: [UTType] = [.markdown]
var attributedText = AttributedString()
func reader(configuration: sending ReadConfiguration) -> sending FileWrapperDocumentReader<String> {
FileWrapperDocumentReader(configuration) { fileWrapper in
guard let data =
fileWrapper.regularFileContents else {
throw CocoaError(.fileReadCorruptFile)
}
return String(decoding: data, as: UTF8.self)
}
}
@MainActor
func apply(snapshot: sending String, previous: sending String?) async throws {
attributedText = try AttributedString(
markdown: snapshot
)
}
}Present a read-only document with DocumentGroup using the viewer initializer:
DocumentGroup { document in
MarkdownView(document: document)
} makeReadableDocument: { configuration, context in
MarkdownViewer()
}Set CFBundleTypeRole to Viewer in your Info.plist for read-only document types.