UIDocument not saving to file despite indicating success UIDocument not saving to file despite indicating success swift swift

UIDocument not saving to file despite indicating success


The way the initial file generation works for me is:

    let doc = YourUIDocumentClass(fileURL: fileURL)     doc.save(to: fileURL, for: .forCreating) { success in        ...                }

Then modify the file and then do:

    doc.save(to: fileURL, for: .forOverwriting)  { success in        ...                }

when done. And subsequent accesses to the file are done by:

    doc.open() { success in        ...    }    doc.close() { success in        ...                }

You might also need to do a:

    doc.updateChangeCount(.done)

while the file is open to tell the document there are unsaved changes. Just setting this will cause a save after a few seconds. You don't even need the close to do that.

The ... means that you either have to nest all these or make sure there is enough time between them so they are completed.


In addition to the above answers, another cause of this can be that there's an error during the save process unrelated to contents(forType:).

For example, if you implement fileAttributesToWrite(to:for:) and throw an error, then this can cause a UIDocumentState.savingError even though contents(forType:) returns the correct data.


So according to

https://developer.apple.com/reference/uikit/uidocument

It looks like the save function isn't actually for saving a document. My understanding from reading it is that save is only for creating a new document. I understand that you are using the .forOverwriting to just save over it but there may be something in iCloud that wont let the complete overwrite happen.

In your doSaveAndClose method try calling

self.saveFile?.close(completionHandler: self.didClose)

by itself. You may have to do some type of if query where you check if the file exist. If it doesn't then call the .save(), else call the .close function. It seems that no matter what when the document it closed it saves changes.