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:

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

Storing document data in a class instance