跳转至
Protocol

ReferenceFileDocument

The protocol used to serialize a reference type document to and from a file.

Declaration

protocol ReferenceFileDocument : ObservableObject

Overview

Conform to this protocol to move a document between its file representation and its "swift-usable" representation.

This protocol is very similar to FileDocument, with the difference being whether the data is stored as a class (reference type) or a struct (value type). Use the two protocols like this:

While the two protocols are similar, ReferenceFileDocument has the unique challenge of the user editing a document while it is being written to a file. For this reason, Snapshot must be used. See the example for more details.

Don't worry about thread safety when using ReferenceFileDocument, since deserialization and serialization are done on a background thread.

  • Note: If your app will have documents, it very likely will be easiest to begin from Apple's own Document app template. To do this, go to File > New > Project, and then use Document App.

Example

App structure

To begin, update the scene definition to use DocumentGroup.

import SwiftUI

@main
struct ExampleApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: { ExampleDocument() }) { file in
            ContentView(document: file.$document)
        }
    }
}

FileDocument conformance

Next, conform to the FileDocument protocol by implementing these properties:

import SwiftUI
import UniformTypeIdentifiers

struct ExampleDocument: FileDocument {
    var text: String

    init(text: String = "This is a brand new document! 📃") {
        self.text = text
    }

    // A
    static var readableContentTypes: [UTType] { [.exampleText] }

    // B
    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
            let string = String(data: data, encoding: .utf8)
        else {
            throw CocoaError(.fileReadCorruptFile)
        }
        text = string
    }

    // C
    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        let data = text.data(using: .utf8)!
        return .init(regularFileWithContents: data)
    }
}

View implementation

Finally, use the TextEditor view to edit the document file.

import SwiftUI

struct ExampleView: View {
    @Binding var document: ExampleDocument

    var body: some View {
        TextEditor(text: $document.text)
    }
}

UTType settings

In order for any of this to work, your Xcode project will have to define a document type. To do this, follow these steps:

  1. Go to the Xcode project settings.
  2. Click on your target to the left.
  3. Expand the Document Types tab.
  4. Click Click here to add additional document type properties
  5. Make the Key NSUbiquitousDocumentUserActivityType.
  6. Ensure the Type is String.
  7. Make the Value $(PRODUCT_BUNDLE_IDENTIFIER).example-document.
  8. Change the Types (top right) to com.example.plain-text.

Lastly, in your ExampleDocument.swift file, extend UTType:

import SwiftUI
import UniformTypeIdentifiers

extension UTType {
    static var exampleText: UTType {
        UTType(importedAs: "com.example.plain-text")
    }
}

Availability

iOS 14.0+

macOS 11.0+

Topics


Instance Method

fileWrapper(snapshot:configuration:) Serializes the document from a snapshot with the specified configuration.

snapshot(contentType:) Creates a snapshot of the current document, which will be used for serialization, while self becomes editable by the user.


Type Property

readableContentTypes The types the ReferenceFileDocument document is able to open.

writableContentTypes The types that a reference file document is able to save or export to.

writableContentTypes The types that a reference file document is able to save or export to.


Initializer

init(configuration:) Initialize the reference file document from the contents of a file.


Type Alias

ReadConfiguration A type alias for referring to the configuration for reading document contents.

WriteConfiguration A type alias used for the configuration when writing a reference file document.


Associated Type

Snapshot The type of the the document snapshot used for serialization in parallel to the main document being editable.