Saving data with UserDefaults — #iOS10

Our 10th iOS post! Boom! and other such clichéd words of success! A smaller post today — how to save small pieces of information in your app such that when the app is used again, the information is still there.

There are lots of different ways to store info in apps, but today we’ll use UserDefaults which is a super handy way to store small amounts of info.

To store something in UserDefaults we first create an instance of them so we create a new variable, call it anything you want, here I choose to call it “defaults”:

then we do things like:

which is storing the value “Andy” in UserDefaults for the key “name”.

Note that I can call the key anything, so I could have written:

But — when you want to retrieve that value from UserDefaults, you must use the key that you gave it earlier:

This creates a new variable called “name” and stores in it the value for the key “whatever”.

We can also store other data-types, not just Strings like above:

and to get it back:

Why would we use UserDefaults?

For a whole heap of reasons — if we want to store a Top Score in a game, if we want to remember the user’s name — pretty much any small pieces of info we’d like the app to “remember”.

A practical example

Create a new app with one View Controller. In the Main.storyboard drag out a TextField, a Button and a Label, like this:

Open the Assistant Editor (via the little button with the two circles) to see the ViewController.swift file beside the Storyboard.

Control-drag from the Label to create an Outlet variable, call it something like “displayLabel”:

resulting in:

Do the same for the TextField, here I call it “textField”:

resulting in:

and finally, add an Action for the Button (not an Outlet):

which looks like:

Ok, they’re all hooked up. Now add this code to the onButton function:

This is checking first if the TextField (which the user will use to enter her/his name) is not empty. If it isn’t it stores the value from the TextField to UserDefaults, using the key “name”.

Now — in viewDidLoad (which is ran everytime the ViewController is loaded onto the screen), add this code:

so it looks like this:

This checks if there is a value stored in UserDefaults for the key “name”. If there is, it displays it on screen in our label.

So, run the app! You should see:

Type in a name and hit the Submit button:

Now, run the app again! You should see this time:

Amazing! The Label is now showing the name we stored in UserDefaults!

If you liked this please hit the little heart recommend button below! Any issues or comments just let me know. Thanks, Andy

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store