Basic File Reading and Writing Using Swift in iOS 8


  • Share on Pinterest

At some point every application developer has to start dealing with writing and reading to and from the file system, which is actually pretty straight forward with iOS 8. Here is a super simple example using a basic string. We will get more complex in the future!

We are going to create a simple interface with a text field to enter some text, a label to display text read in from a file and two simple buttons for saving and reading the file.

Create a new application

First create a new Xcode iOS application with a single user interface making sure to select the Swift language. Device can be anything, it does not matter for this project, I went with iPhone just to get the screenshots to fit … those Retina resolutions can be troublesome on a MacBook Air πŸ™‚

Create the interface

  1. Add a new textfield object for entering text.
  2. Add a button below the text field and change the label to ‘Write'.
  3. Add another button and change the label to ‘Read'.
  4. Below the read button add a label object. I left my one saying β€˜Label’ so I could clearly see the text change occurring.

Storyboard with Objects

Hook em up!

Using the method you prefer create two @IBOutlets for the text field and label, and create two @IBAction's for the buttons in the ViewController.swift file.

@IBOutlet weak var entryField: UITextField!
@IBOutlet weak var displayField: UILabel!

@IBAction func writeButton(sender: UIButton) 
}

@IBAction func readButton(sender: UIButton) 
}

So the entire viewController code should look like

//
//  ViewController.swift
//  ReadWrite Example
//
//  Created by Peter Witham on 5/13/15.
//  Copyright (c) 2015 Peter Witham. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    
    @IBOutlet weak var entryField: UITextField!
    @IBOutlet weak var displayField: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func writeButton(sender: UIButton) {
    }

    @IBAction func readButton(sender: UIButton) {
    }

}

Saving the text

I am not going to cover validation of the entry field or any of that in this article, I'm just going to get down to the important parts of writing. However we will check to see if the file was written successfully or not using a simple console statement for this example. I mention this because it is important to handle all out comes when writing and reading files. Unless you like awkward program crashes and angry users!

Inside the func writeButton First create a constant with the value of the text field

let myTextString = NSString(string: entryField.text!)

Now we will create a constant that holds the path to the file, we will take advantage of NSTemporaryDirectory() which returns to us the current user directory, when creating a proper application I recommend storing elsewhere but this keeps thing simple to get the idea across. We will append a file name to the location.

let destinationPath = NSTemporaryDirectory() + "my_file.txt"

One last variable, we need to create one to hold any errors that might occur.

var error:NSError?

Now we will attempt to write the file using writeToFile(path:atomically:encoding:error) which is available through our myTextString constant.

A little explanation of the arguments.

path:String is where we will save the file

atomically:Bool gives the option to save to a temporary location and then copy to our final location, which is good should our application crash or something bad happen during the process.

encoding:UInt is the encoding we store the file in.

error:NSErrorPointer will hold any errors that might occur so we can access them and deal with the problem(s) gracefully.

let written = myTextString.writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding, error: &error)

Finally we will check and see if the file wrote successfully or not and do something based on the outcome. For this example we will simply write to the console using println

if written {
    println("We wrote the file to \(destinationPath)")
}  else 
    println("There was a problem: \(error)")
}

That is the saving part completed and the entire writing function should look like

@IBAction func writeButton(sender: UIButton) {
        let myTextString = NSString(string: entryField.text!)
        let destinationPath = NSTemporaryDirectory() + "my_file.txt"
        var error:NSError?
        let written = myTextString.writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
    }

Now on to reading the file in when performing the “Read” button action.

Read the file contents in and display

To do this is not that dissimilar to writing the file, we create a path to the file and use contentsOfFile to read it and assign the results to a constant. We then unwrap and check that constant to see if the loading was successful or not. If the answer is yes then we display the string in displayField and if not we write to the console.

Inside func readButton First we create the path (there is a reason I created two paths to the file, you will see later)

let path = NSTemporaryDirectory() + "my_file.txt"

Now we read the file into a constant

let readFile:NSString? = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String

Finally just like before we check the constant by unwrapping it and doing something with the results (or lack of).

if let fileContents = readFile {
    displayField.text = fileContents as String
} else {
    println("Opps there was a problem reading the file contents")
}

The contents of the read func should look like

@IBAction func readButton(sender: UIButton) {
        let path = NSTemporaryDirectory() + "my_file.txt"
        let readFile:NSString? = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String
        if let fileContents = readFile {
            displayField.text = fileContents as String
        } else {
        println("Opps there was a problem reading the file contents")
        }
    }

Testing time

And that is all you need, go ahead and run the application, enter some text and hit the “Write” button. The console should show whether or not the save was successful. Now try the “Read” button, the text you entered and saved should now appear in the label, if not look to the console.

Hopefully everything worked, but let's force an error reading the file back so you can check that it handles the problem without crashing the application. Remember that we created a path for reading the file back in? Change the readButton function so the path points to a different file.

let path = NSTemporaryDirectory() + "my_other_file.txt"

Now try the “Read” button again, this time it should fail to find the file and write to the console!

Wrap up

Whilst this is a super simple example and not something you are likely to want to do in practice it does give you a basic understanding of reading and writing files. In the future we will look at a more practical example where you might want to save complex objects and read them back in.