我正在处理一个将数据保存为 PDF 的项目。代码是:
// Save PDF Data
let recipeItemName = nameTextField.text
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
pdfData.writeToFile("\(documentsPath)/\(recipeFileName).pdf", atomically: true)
我可以在另一个 ViewController
中的单独 UITableView
中查看文件。当用户滑动 UITableViewCell
时,我希望它也从 .DocumentDirectory
中删除项目。我的 UITableView
删除代码是:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
savedPDFFiles.removeAtIndex(indexPath.row)
// Delete actual row
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// Deletion code for deleting from .DocumentDirectory here???
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
我试过在网上找到答案,但找不到 Swift 2 的任何答案。有人可以帮忙吗?
我试过使用这个但没有成功:
var fileManager:NSFileManager = NSFileManager.defaultManager()
var error:NSErrorPointer = NSErrorPointer()
fileManager.removeItemAtPath(filePath, error: error)
我只想删除刷过的特定项目,而不是 DocumentDirectory
中的所有数据。
最佳答案
removeItemAtPath:error:
是 Objective-C 版本。对于 swift,您需要 removeItemAtPath
,如下所示:
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {}
在 swift 中,当使用将 throw
的方法时,这是一种非常常见的模式 - 在调用前加上 try
并包含在 do-catch中
。与在 objective-c 中相比,您将更少地使用错误指针。相反,需要捕获错误,或者像上面的代码片段一样忽略错误。要捕获并处理错误,您可以像这样删除:
do {
let fileManager = NSFileManager.defaultManager()
let documentDirectoryURLs = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let filePath = documentDirectoryURLs.first?.URLByAppendingPathComponent("myFile.pdf").path {
try fileManager.removeItemAtPath(filePath)
}
} catch let error as NSError {
print("ERROR: \(error)")
}
关于iOS:使用 Swift2 删除 .DocumentDirectory 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051983/