Contents

DocumentWriter

A type that writes a document’s content to a file.

Declaration

protocol DocumentWriter<Snapshot>

Overview

SwiftUI calls your document’s snapshot(contentType:) on the main actor to capture the current state, then obtains a DocumentWriter from writer(configuration:) and invokes write(content:to:previous:progress:) in the background with coordinated file access.

Use FileWrapperDocumentWriter for cases cases that don’t require custom file write logic. Implement a DocumentWriter when you need direct URL access or streaming writes:

struct ImageWriter: DocumentWriter {
    @concurrent
    func write(content image: sending CGImage, to destination: URL,
        previous: sending CGImage?, progress: consuming Subprogress
    ) async throws {
        guard let imageDestination =
            CGImageDestinationCreateWithURL(
                destination as CFURL,
                UTType.jpeg.identifier as CFString,
                1, nil
            ) else {
            throw CocoaError(.fileWriteUnknown)
        }
        CGImageDestinationAddImage(
            imageDestination, image, nil
        )
        guard CGImageDestinationFinalize(
            imageDestination
        ) else {
            throw CocoaError(.fileWriteUnknown)
        }
    }
}

Topics

Writing a document

See Also

Reading and writing documents