write(snapshot:to:previous:progress:)
Writes the document content to disk.
Declaration
@concurrent func write(snapshot: sending Self.Snapshot, to destination: sending Self.Destination, previous: sending Self.Snapshot?, progress: consuming Subprogress) async throwsParameters
- snapshot:
The snapshot to write to disk.
- destination:
The file URL to write to.
- previous:
The last successfully written snapshot, or
nilon the first save. Compare tocontentto write only what changed in package documents. - progress:
A
Subprogressvalue to report writing progress. Consume it once withreporter(totalCount:)and callcomplete(count:)as units finish.
Discussion
SwiftUI calls this method in the background after obtaining a snapshot via snapshot(contentType:). Perform all serialization and disk access here.
For most documents, use FileWrapperDocumentWriter instead of implementing a custom writer. Only implement write yourself when you need capabilities FileWrapperDocumentWriter doesn’t provide — such as direct URL access for Core Graphics, AVFoundation, or other frameworks that operate on file paths:
@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)
}
}