The delete text file operation pretty much delete an existing text file in the app’s Documents folder. Further more, the app user is usually the one who initiate this operation by tapping a button in a table view cell.
Code presented on this page assume you are using Xcode 7.0 and Swift version 2.0. So if you are using a 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 delete a cell from the table view |
|
Here’s a quick time video of the delete a text file 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) }
That’s all for today. Next week, you will implement the find text file operation in the NiftyTextFile project. Until then, comments are welcomed. 🙂
One response
Thank you so much for your teaching!
I’m learning..