跳转至
Protocol

FileDocument

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

Declaration

protocol FileDocument

Overview

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

This protocol is very similar to ReferenceFileDocument, 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:

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)
    }
}
Note that in this example, we create a custom readableContentTypes called UTType.exampleText.

View implementation

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

import SwiftUI

struct ContentView: 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(configuration:) Serialize the document with the specified configuration.


Type Property

readableContentTypes The file types the FileDocument document is able to open.

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

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


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 file document.


Initializer

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