iOS: 使用 Swift2 删除 .DocumentDirectory 中的文件

iOS: Delete file in .DocumentDirectory using Swift2

我正在处理一个将数据保存为 PDF 的项目。代码是:

// Save PDF Data

let recipeItemName = nameTextField.text

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

pdfData.writeToFile("\(documentsPath)/\(recipeFileName).pdf", atomically: true)

我可以在单独的 UITableView 中查看文件,而我在另一个 ViewController 中。当用户滑动 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 中的所有数据。

您要做的是从已编辑的单元格中检索 recipeFileName 以重建文件路径。

目前还不清楚您是如何填充 UITableViewCell 数据的,因此我将介绍最常见的情况。

假设您有一组文件用于填充 dataSource

let recipeFiles = [RecipeFile]()

使用 RecipeFile 结构

struct RecipeFile {
   var name: String
}

tableView(_:cellForRowAtIndexPath:) 中,您可能会像这样设置食谱文件:

cell.recipeFile = recipeFiles[indexPath.row]

所以在tableView(_:commitEditingStyle:forRowAtIndexPath:)中,你可以像这样检索文件名:

let recipeFile = recipeFiles[indexPath.row]

并删除你的文件

var fileManager:NSFileManager = NSFileManager.defaultManager()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let filePath = "\(documentsPath)/\(recipeFile.name).pdf"
do {
    fileManager.removeItemAtPath(filePath, error: error)
} catch _ {
    //catch any errors
}

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)")
    }