Contents

ReferenceFileDocument

A type that you use to serialize reference type documents to and from file.

Declaration

@preconcurrency protocol ReferenceFileDocument : ObservableObject, Sendable

Overview

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:

Because ReferenceFileDocument is a reference type, SwiftUI can’t detect changes to your document’s properties on its own. Register an undo action with the environment’s UndoManager whenever you mutate the document, for example by calling UndoManager/registerUndo(withTarget:handler:).

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)
    }
}

Topics

Reading a document

Getting a snapshot

Writing a document

See Also

Deprecated