Why is calling .save
on an external (iCloud) UIDocument so tricky? :frowning: It either:
- takes forever and doesn't save, or
- save operation fails, despite of calling
startAccessingSecurityScopedResource()
prior to the save call. - saves sometimes, randomly!
So unsure about what am I missing here. Here's my code for the saving bit (I am only dealing with plain text files):
private func saveDocument() {
if (document == nil) { return }
saveLabel.text = "Saving.."
saveLabel.isHidden = false
saveIndicator.isHidden = false
saveIndicator.startAnimating()
if (!(document?.fileURL.startAccessingSecurityScopedResource() ?? false)) {
self.saveLabel.text = "File is busy!"
self.saveIndicator.stopAnimating()
self.saveIndicator.isHidden = true
Common.alert(view: self, message: "File is busy! Please try again in a bit.")
self.showRetrySaveButton()
return
}
document?.save(to: fileURL!,
for: .forOverwriting,
completionHandler: {(success: Bool) -> Void in
self.saveIndicator.stopAnimating()
self.saveIndicator.isHidden = true
if success {
self.document?.fileURL.stopAccessingSecurityScopedResource()
self.saveLabel.text = "Saved!"
self.hideSaved()
self.hideDoneButton()
} else {
self.saveIndicator.isHidden = true
self.saveLabel.text = "Save failed!"
Common.alert(view: self, message: "File save failed! Please try again.")
self.showRetrySaveButton()
}
})
}
The text box that I use for saving keeps the text loaded even after the save operation, which is why I don't really close the UIDocument (do I really need to close the document before say, opening the same document again or opening another one?). I only save the changes when the editing is finished or done button is pressed.
Help is much appreciated!