Text File Workshop: Delete Text File

The delete text file operation pretty much deletes an existing text file in the app’s Documents folder. Furthermore, the app user is usually the one who initiates this operation by tapping a button in a table view cell.

Code presented on this page assumes you are using Xcode 7.0 and Swift version 2.0. So if you are using an older or newer version of Swift, it may produce errors. Fix them by using Xcode’s Fix-it tool. Also, I assume you aren’t a newbie to the Swift Programming Language, and you know your way around Xcode Integrated Development Editor.

In today’s workshop, you will implement the delete file operation in the NiftyTextFile project. Here is a User Interaction table of this operation.

User Action App Response
The user deletes a cell from the table view
  • Remove the text file from the app’s Documents folder
  • Remove the text file from the table view’s data source
  • Animate deletion of the swiped table view cell

Here’s a QuickTime video of the text file deletion operation in action.
Now, here’s the first piece of code to implement the delete text file operation. Enter it in the TextFileManager class.

// This function delete a text file from the sandbox's Documents folder
func deleteFileFromDocumentsFolder(fileToDelete: String) -> Bool {
  var fileDeleted = false
  let sourceFile = getDocumentsDirectory().stringByAppendingString("/"+fileToDelete)
  let fileManager = NSFileManager.defaultManager()
    
  do {
    try fileManager.removeItemAtPath(sourceFile)
    fileDeleted = true
  } catch let fileDeleteError as NSError {
    print("File DELETE ERROR:\n\(fileDeleteError)")
  }
    
  return fileDeleted
}

Here is the second piece of code to implement the delete text file operation. Put it in the FileListViewController.swift file’s commitEditingStyle() function. Once you’ve done that, run the app on the Simulator and delete one or more cells from the File List’s table view.

if editingStyle == .Delete {
  let fileToDelete = fileList[indexPath.row]
  File.deleteFileFromDocumentsFolder(fileToDelete)
  fileList.removeAtIndex(indexPath.row)
  tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}

next-iconThat’s all for today. Next week, you will implement the find text file operation in the NiftyTextFile project. Until then, comments are welcomed. 🙂