I have a project I'm working on that saves data to a PDF. The code for this is:
// Save PDF Data
let recipeItemName = nameTextField.text
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
pdfData.writeToFile("\(documentsPath)/\(recipeFileName).pdf", atomically: true)
I'm able to view the files in a separate UITableView I have in another ViewController. When the user swipes the UITableViewCell I want it to also delete the item from the .DocumentDirectory. My code for the UITableView delete is:
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
}
}
I've tried finding the answer online but can't find anything for Swift 2. Can someone please help?
I've tried working with this but with no luck:
var fileManager:NSFileManager = NSFileManager.defaultManager()
var error:NSErrorPointer = NSErrorPointer()
fileManager.removeItemAtPath(filePath, error: error)
I just want to remove the particular item swiped and not all data in the DocumentDirectory.
removeItemAtPath:error: is the Objective-C version. For swift, you want removeItemAtPath, like this:
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {}
In swift, this is a pretty common pattern when working with methods that will throw - prefix the call with try and enclose in do-catch. You will be doing less with error pointers then you would in objective-c. Instead, the errors need to be caught or, as in the snippet above, ignored. To catch and handle the error, you could do your delete like this:
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)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With