Cha*_*Guy 3 uitableview delete-file ios swift2
我有一个项目,我正在将数据保存为PDF.这个代码是:
// Save PDF Data
let recipeItemName = nameTextField.text
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
pdfData.writeToFile("\(documentsPath)/\(recipeFileName).pdf", atomically: true)
Run Code Online (Sandbox Code Playgroud)
我能够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
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试在线找到答案,但找不到Swift 2的任何内容.有人可以帮忙吗?
我尝试过这个,但没有运气:
var fileManager:NSFileManager = NSFileManager.defaultManager()
var error:NSErrorPointer = NSErrorPointer()
fileManager.removeItemAtPath(filePath, error: error)
Run Code Online (Sandbox Code Playgroud)
我只是想删除特定的项目,而不是所有数据DocumentDirectory.
removeItemAtPath:error:是Objective-C版本.对于swift,你想要removeItemAtPath,像这样:
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {}
Run Code Online (Sandbox Code Playgroud)
在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)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1126 次 |
| 最近记录: |