Did you find this helpful? Why not support me to bring you even more content.
Click here to Buy Me a Coffee and say Thanks!

DISCLAIMER: This post is older than one year and maybe out of date.

Basic File Reading and Writing Using Swift in iOS 8

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.

So the entire viewController code should look like

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

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.

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

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.

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

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

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)

Now we read the file into a constant

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

The contents of the read func should look like

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.

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.