When creating a class conforming to ReferenceFileDocument, how do you indicate the document needs saving. i.e. the equivalent of the NSDocument's updateChangeCount method?
-
My understanding is, that the App framework uses the published/observable objects to monitor and understand if an update happened. It then call's the snapshot to capture/save the document. The undo manager does not seem to be needed. Xcode 14.2 (14C18)– thiloCommented Feb 11, 2023 at 0:42
5 Answers
I've met the same problem that the SwiftUI ReferenceFileDocument cannot trigger the update. Recently, I've received feedback via the bug report and been suggested to register an undo.
Turns out the update of ReferenceFileDocument can be triggered, just like UIDocument, by registering an undo action. The difference is that the DocumentGroup explicitly implicitly setup the UndoManager via the environment.
For example,
@main
struct RefDocApp: App {
var body: some Scene {
DocumentGroup(newDocument: {
RefDocDocument()
}) { file in
ContentView(document: file.document)
}
}
}
struct ContentView: View {
@Environment(\.undoManager) var undoManager
@ObservedObject var document: RefDocDocument
var body: some View {
TextEditor(text: Binding(get: {
document.text
}, set: {
document.text = $0
undoManager?.registerUndo(withTarget: document, handler: {
print($0, "undo")
})
}))
}
}
I assume at this stage, the FileDocument is actually, on iOS side, a wrapper on top of the UIDocument, the DocumentGroup scene explicitly implicitly assign the undoManager to the environment. Therefore, the update mechanism is the same.
-
I'm confused - you say "DocumentGroup scene explicitly assign the undoManager to the environment" but where are you doing that?– GrimxnCommented Jan 26, 2021 at 16:24
-
@Grimxn Thanks for spotting it. I was meant "implicitly". The DocumentGroup implicitly assign the undoManager to the environment. On the contrary, ReferenceDocumentGroup doesn't assign the undoManager by default.– zrfrankCommented Jan 26, 2021 at 16:44
-
Ok - That makes sense! I’m finding ReferenceFileDocument just a wee bit obscure!– GrimxnCommented Jan 26, 2021 at 16:47
-
1At least in my demo projects, as long as conflict resolution is required, I've to wrap the UIDocument/NSDocument myself anyway. Eventually, I've to wrote my own PsudoDocumentGroup. Have fun.– zrfrankCommented Jan 26, 2021 at 16:53
ReferenceFileDocument exists for fine grained controll over the document. In comparison, a FileDocument has to obey value semantics which makes it very easy for SwiftUI to implement the undo / redo functionality as it only needs to make a copy before each mutation of the document.
As per the documentation of the related DocumentGroup initializers, the undo functionality is not provided automatically. The DocumentGroup will inject an instance of an UndoManger into the environment which we can make use of.
However an undo manager is not the only way to update the state of the document. Per this documentation AppKit and UIKit both have the updateChangeCount method on their native implementation of the UI/NSDocument object. We can reach this method by grabbing the shared document controller on macOS from within the view and finding our document. Unfortunately I don't have a simple solution for the iOS side. There is a private SwiftUI.DocumentHostingController type which holds a reference to our document, but that would require mirroring into the private type to obtain the reference to the native document, which isn't safe.
Here is a full example:
import SwiftUI
import UniformTypeIdentifiers
// DOCUMENT EXAMPLE
extension UTType {
static var exampleText: UTType {
UTType(importedAs: "com.example.plain-text")
}
}
final class MyDocument: ReferenceFileDocument {
// We add `Published` for automatic SwiftUI updates as
// `ReferenceFileDocument` refines `ObservableObject`.
@Published
var number: Int
static var readableContentTypes: [UTType] { [.exampleText] }
init(number: Int = 42) {
self.number = number
}
init(configuration: ReadConfiguration) throws {
guard
let data = configuration.file.regularFileContents,
let string = String(data: data, encoding: .utf8),
let number = Int(string)
else {
throw CocoaError(.fileReadCorruptFile)
}
self.number = number
}
func snapshot(contentType: UTType) throws -> String {
"\(number)"
}
func fileWrapper(
snapshot: String,
configuration: WriteConfiguration
) throws -> FileWrapper {
// For the sake of the example this force unwrapping is considered as safe.
let data = snapshot.data(using: .utf8)!
return FileWrapper(regularFileWithContents: data)
}
}
// APP EXAMPLE FOR MACOS
@main
struct MyApp: App {
var body: some Scene {
DocumentGroup.init(
newDocument: {
MyDocument()
},
editor: { file in
ContentView(document: file.document)
.frame(width: 400, height: 400)
}
)
}
}
struct ContentView: View {
@Environment(\.undoManager)
var _undoManager: UndoManager?
@ObservedObject
var document: MyDocument
var body: some View {
VStack {
Text(String("\(document.number)"))
Button("randomize") {
if let undoManager = _undoManager {
let currentNumber = document.number
undoManager.registerUndo(withTarget: document) { document in
document.number = currentNumber
}
}
document.number = Int.random(in: 0 ... 100)
}
Button("randomize without undo") {
document.number = Int.random(in: 0 ... 100)
// Let the system know that we edited the document, which will
// eventually trigger the auto saving process.
//
// There is no simple way to mimic this on `iOS` or `iPadOS`.
let controller = NSDocumentController.shared
if let document = controller.currentDocument {
// On `iOS / iPadOS` change the argument to `.done`.
document.updateChangeCount(.changeDone)
}
}
}
}
}
Unfortunatelly SwiftUI (v2 at this moment) does not provide a native way to mimic the same functionality, but this workaround is still doable and fairly consice.
Here is a gist where I extended the example with a custom DocumentReader view and a DocumentProxy which can be extended for common document related operations for more convenience: https://gist.github.com/DevAndArtist/eb7e8aa5e7134610c20b1a7aca358604
-
One refinement suggestion is to ensure that the call to updateChangeCount(.changeDone) always happens on the Main thread. Commented Dec 6, 2021 at 10:32
The ReferenceFileDocument is ObservableObject, so you can add any trackable or published property for that purpose. Here is a demo of possible approach.
import UniformTypeIdentifiers
class MyTextDocument: ReferenceFileDocument {
static var readableContentTypes: [UTType] { [UTType.plainText] }
func snapshot(contentType: UTType) throws -> String {
defer {
self.modified = false
}
return self.storage
}
@Published var modified = false
@Published var storage: String = "" {
didSet {
self.modified = true
}
}
}
-
I understand this solution would enable me to tell if any relevant property had been changed. However, what I'm looking for is a way to inform SwiftUI that the document needs saving.In the old NSDocument world, you could call
func updateChangeCount(_ change: NSDocument.ChangeType), if you weren't using the UndoManager. What is the SwiftUI alternative? Commented Sep 10, 2020 at 19:01
There is a way to access updateChangeCount directly with use of NSViewRepresentable. The only thing I'm trying to work out at the moment is how to remove the binding as it prevents the document class from deallocating once the window is closed.
struct NSWindowAccessor: NSViewRepresentable {
@Binding var window: NSWindow?
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async {
self.window = view.window
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}
struct ContentView: View {
@State private var window: NSWindow?
func setDocModified(){
if window != nil {
if(window!.windowController?.document != nil){
window!.windowController!.document?.updateChangeCount(.changeDone)
}
}
}
var body: some View {
Button("document modified"){
setDocModified()
}
EmptyView()
.background(NSWindowAccessor(window: $window))
}
}
You can use the undo manager, but if your changes are conceptually not undoable (e.g. progressing in a quiz), you can simply use the underlying document controller as before:
@Environment(\.undoManager) var undoManager
...
Button("Dirty the Doc"){
if let document = documentController.currentDocument {
document.updateChangeCount(.changeDone)
}
}
(Took me a few years to find this, but it makes life so much better.)