ReferenceFileDocument
A type that you use to serialize reference type documents to and from file.
Declaration
@preconcurrency protocol ReferenceFileDocument : ObservableObject, SendableOverview
To store a document as a reference type — like a class — create a type that conforms to the ReferenceFileDocument protocol and implement the required methods and properties. Your implementation:
Provides a list of the content types that the document can read from and write to by defining readableContentTypes. If the list of content types that the document can write to is different from those that it reads from, you can optionally also define writableContentTypes.
Loads documents from file in the init(configuration:) initializer.
Stores documents to file by providing a snapshot of the document’s content in the snapshot(contentType:) method, and then serializing that content in the fileWrapper(snapshot:configuration:) method.
Ensure that types that conform to this protocol are Sendable. In particular, SwiftUI calls the protocol’s methods from different isolation domains. Don’t perform serialization and deserialization on MainActor.
final class PDFDocument: ReferenceFileDocument {
struct Storage {
var contents: Data
}
static let readableContentTypes: [UTType] = [.pdf]
let storage: Mutex<Storage>
required init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents else {
throw CocoaError(.fileReadCorruptFile)
}
self.storage = .init(.init(contents: data))
}
func snapshot(contentType: UTType) throws -> Data {
storage.withLock { $0.contents }
}
func fileWrapper(snapshot: Data, configuration: WriteConfiguration) throws -> FileWrapper {
return FileWrapper(regularFileWithContents: snapshot)
}
}