UIDocument not saving to file despite indicating success

前端 未结 3 619
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 04:45

I\'m trying to open, modify, and save a file in iCloud Drive using UIDocument. When I call save(to:for:completionHandler:) with the file location and u

相关标签:
3条回答
  • 2021-02-05 04:51

    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.

    0 讨论(0)
  • 2021-02-05 04:56

    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.

    0 讨论(0)
  • 2021-02-05 04:57

    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.

    0 讨论(0)
提交回复
热议问题