我正在使用Swift 4,我需要知道如何使用UIDocument删除。我知道如何设置url路径:
if let url = try? FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
).appendingPathComponent("Inbox/test.txt") {
falloutFileHandler = FalloutTextFileHandler(fileURL: url)
}其中falloutFileHandler是UIDocument类型,falloutFileHandler有一个名为falloutFile的属性,该属性将字符串存储为名为“data”的属性。
我知道怎么打开这个文件:
falloutFileHandler?.open { success in
if success {
if let theText = self.falloutFileHandler?.falloutFile?.data {
self.textView.text = self.text!
} else {
print("Something went wrong")
}
}
}但我不知道如何使用UIDocument删除文件。提前谢谢你。
另外,有没有一种方法可以打印出为什么某些东西在打开时不成功?比如打印(Error)或类似的东西,而不是像我那样做打印(“出了问题”)?
发布于 2018-05-09 14:33:00
UIDocument用作iOS应用程序文档的底层容器。它知道如何读取文档,还原文档,比较文档的版本(例如,您的本地文档可能与iCloud中存储的文档不同,等等)。
但是,您不能使用UIDocument的内置API来删除自身。您要么必须在子类中实现(因为只有您的子类确切地知道文档存储在哪里/如何存储),要么很可能需要使用FileManager,就像您如何使用它来选择最初从何处加载/读取UIDocument (或者在您的例子中是FalloutTextFileHandler)。
要使用后者,您可以执行如下操作:
do {
let fm = FileManager.default
if let url = try fm.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
).appendingPathComponent("Inbox/test.txt") {
// the actual delete method
try FileManager.default.removeItem(at: url)
}
} catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}}
https://stackoverflow.com/questions/50244300
复制相似问题