我試圖使用UIDocument
在iCloud Drive中打開,修改和保存文件。當我使用文件位置調用save(to:for:completionHandler:)
並將.forOverwriting
用於UIDocumentSaveOperation
時,它會以success = true
的狀態完成。但是,iCloud文件(如桌面和iOS文件瀏覽器中所示)不會更新,並且在重新打開文件時,不會顯示更改。我已驗證contents(forType:)
在保存時會返回正確(已修改)的文件內容。儘管指示成功,UIDocument仍未保存到文件
(注:我已經看過this question,但它不是非常有幫助)
這裏是代碼的有關章節:
MainViewController.swift:
var saveFile: SBDocument?
@IBAction func bbiOpen_pressed(_ sender: UIBarButtonItem) {
if saveFile == nil {
let importMenu = UIDocumentMenuViewController(documentTypes: self.UTIs, in: .import)
importMenu.delegate = self
importMenu.popoverPresentationController?.barButtonItem = bbiOpen
self.present(importMenu, animated: true, completion: nil)
} else {
willClose()
}
}
func willClose(_ action: UIAlertAction?) {
if saveFile!.hasUnsavedChanges {
dlgYesNoCancel(self, title: "Save Changes?", message: "Would you like to save the changes to your document before closing?", onYes: doSaveAndClose, onNo: doClose, onCancel: nil)
} else {
doSaveAndClose(action)
}
}
func doSaveAndClose(_ action: UIAlertAction?) {
saveFile?.save(to: saveFileURL!, for: .forOverwriting, completionHandler: { Void in
self.saveFile?.close(completionHandler: self.didClose)
})
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
saveFile = SBDocument(fileURL: url)
saveFile!.open(completionHandler: { success in self.finishOpen(didCompleteSuccessfully: success) })
}
func finishOpen(didCompleteSuccessfully result: Bool) {
if result {
print(saveFile!.localizedName)
saveFileURL = saveFile!.fileURL
saveFileName = saveFile!.localizedName
self.navTitleBar.prompt = saveFileName
bbiOpen.title = NSLocalizedString("titleClose", comment: "Close")
bbiOpen.style = .plain
} else {
saveFile = nil
}
}
@IBAction func bbiSave_pressed(_ sender: UIBarButtonItem) {
self.saveFile!.save(to: self.saveFileURL!, for: .forOverwriting, completionHandler: self.didSave)
}
func didSave(_ success: Bool) {
guard success else {
print("Error saving soundboard file to \(String(describing: saveFileURL))")
return
}
print("File saved successfully")
}
SBDocument.swift:
class SBDocument: UIDocument {
override var fileType: String? { get { return "com.whitehatenterprises.SoundBoardFX.sbd" } }
override var savingFileType: String? { get { return "com.whitehatenterprises.SoundBoardFX.sbd" } }
override init(fileURL url: URL) {
super.init(fileURL: url)
}
override func contents(forType typeName: String) throws -> Any {
let arr = NSArray(array: SoundEffects)
let data: NSData = NSKeyedArchiver.archivedData(withRootObject: arr) as NSData
return data
}
}
更新: 我真的需要幫助,我已經嘗試了所有我能想到的方法來解決這個問題。任何援助,你可以給我將不勝感激。
@matt對不起,這應該是'.forOverwriting'。我只是暫時改變它,看看它是否有所作爲(它沒有)。 – Matt
而不是downvoting,有人可以提供一些建設性的反饋?我真的需要找到一個答案。 – Matt
觀察「UIDocumentStateChanged」通知。在回調中,你是否碰巧報告過'inConflict'的狀態? –