Text File Workshop: Read Text File

The read text file operation basically fetch a text file’s data from the Documents folder, and store it in a string variable. Let us call that variable, fetchedFileData. At this point, you can do what ever you want with the fetchedFileData variable; for example, you can dump it in the console or in a textView.

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.

Here is a QuickTime movie of the read text file operation you will implement in the NiftyTextFile project today.

Here is a User Interaction table of the read text file operation.

User Action App Response
The user tap a cell on the File List’s table view The app respond by doing the following:

  • Read the selected table View cell’s text file
  • Put the read text file’s data in a string variable
  • Put the selected text file’s name in a string variable
  • Pass the read text file’s data and its name to the UpdatedFileViewController class
  • Assign the selected text file’s name and its data to the Update File’s Label and Text View

Add a New Scene on The Storyboard

In order to implement the read text file operation in the NiftyTextFile project, you have to perform several several tasks. Start by dragging a View Controller from the Object Library and drop it below the Initial scene. Design the scene so it look like this:


Add Cocoa Touch Class in The Project

Next, add a Cocoa Touch class in the project and configure the options window so it look like the image shown below. Next, connect the new View Controller scene to the UpdateFileViewController class, via the Identity inspector.


Do the usual stuff of creating IBOutlets for the view’s Label and Text View object, creating an IBAction function for the view’s Update File button, and adding missing constraints to the scene’s object.

@IBOutlet weak var fileNameLabel: UILabel!
@IBOutlet weak var textView: UITextView!

@IBAction func updateButtonPressed(sender: UIButton) {

Next, connect the scene’s Back button to its Exit object. When prompted, select the “unwindToMainView” Action Segue. Also, connect the List File View Controller scene’s table view cell to the Update File View Controller object. When prompted, select “show” from the Selection Segue menu. Select the segue and set its Identifier attribute to, showUpdateFileView.


Next, modify the UpdateFileViewController’s class to look like this:


The storyboard should look like this now:


The Read Text File Code

Ok, you are ready to add code in the FileListViewController class to implement the read text file operation. Start by adding this function in the TextFileManager class file.

// This function read a text file and return its data to the caller of the function
func readTextFile(fileName: String, path: String) -> String {
    var fileData = String()
    let filePath = getDocumentsDirectory().stringByAppendingString("/"+fileName)
    do {
        fileData = try NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) as String
    } catch {
        print("\nCouldn't read the file for anyone of these reasons:\n➣ The file doesn't exists at the specified location\n➣ Bad file permission\n➣ Bad file name\n➣ Content of the file can't be converted to a Swift String")
    return fileData

Next, enter this code in the FileListViewController.swift file’s prepareForSegue() function. The code pretty much implement tasks listed in above User Interaction table. The dump() statements aren’t needed. They are there so you can see that the read text file operation works.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showUpdateFileView" {
        let indexPath = self.tableView.indexPathForSelectedRow
        let selectedFileName = fileList[indexPath!.row]
        let filePath = File.getDocumentsDirectory().stringByAppendingString("/"+selectedFileName)
        let fileContent: String = File .readTextFile(selectedFileName, path: filePath)
        dump("The text file you selected is '\(selectedFileName)' and it contain this:\n")
        let destinationViewController: UpdateFileViewController = segue.destinationViewController as! UpdateFileViewController
        destinationViewController.fileContent = fileContent
        destinationViewController.selectedFileName = selectedFileName

Switch over to the UpdateFileViewController.swift file and enter these statements, below existing statements that’s in the viewDidLoad() function:

fileNameLabel.text = selectedFileName
oldNote = fileContent
textView.text = oldNote

That’s all the code you have to put the UpdateFileViewController.swift file. When you run the app on your real device or the Simulator, it should work like the one shown in the QuickTime movie presented at the beginning of this post. Further more, you should see the selected text file’s name and its content in the console.

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