Working with User Defaults in SwiftUI

Cache your user's data with UserDefaults.

When creating an application with authentication, it is essential to cache your user's data. Even when the user quits the app, the data should still be there for the next time the user launches the app. We don't want to ask the user to sign in every time they open the app, as that would be bad user experience.


UserDefaults is a class that does just that. It persistently caches the user's preferences (the currency the user prefers for a store app, for example) as well as any other data you would want (the user's ID, their email, etc.). It works as key-value pairs and is very simple to implement.

How to use UserDefaults? 

In your View, add a Text. Let's set it to an empty string for now.

var body: some View {
		Text("")
}

..

Write to UserDefaults

Add an .onAppear modifier to the Text, so that when the Text appears, we want to set the user's email. Create an userEmail variable in the modifier and set it to whatever you want.

Then, call the UserDefaults class, with the standard settings (.standard), and set the email key to the userEmail variable we just created.

var body: some View {
		Text("")
				.onAppear() {
						let userEmail = "swiftuiio@gmail.com"
						UserDefaults.standard.set(userEmail, forKey: "email")
				}
}

..

Read from UserDefaults

At the top of the same file, just after you defined your struct, create another variable, where we'll read the email we saved to our UserDefaults.

let savedEmail = UserDefaults.standard.string(forKey: "email")

..

Finally, replace the empty strings in the Text for the savedEmail variable.

Text(savedEmail)

..

Final code 

The final code will look like this:

struct ContentView: View {
    let savedEmail = UserDefaults.standard.string(forKey: "email")

    var body: some View {
        Text(savedEmail)
            .padding()
            .onAppear() {
                let userEmail = "swiftuiio@gmail.com"
                UserDefaults.standard.set(userEmail, forKey: "email")
            }
    }
}

..

Other examples You can set any type of variable in UserDefaults, it is not limited to strings. Here are some other examples:

// An integer
let userAge = 40
UserDefaults.standard.set(userAge, forKey: "age")

// A boolean
let userIsLoggedIn = true
UserDefaults.standard.set(userIsLoggedIn, forKey: "isLoggedIn")

// A date
let userLastLoginTime = Date()
UserDefaults.standard.set(userLastLoginTime, forKey: "lastLoginTime")

..

Note: 

  • Don't store too much data in your UserDefaults. 
  • Only store the important ones, as too much data in UserDefaults can use too much memory and the first load can be longer each time the user launches the app.

Comments