How to Store User Settings with UserDefaults in SwiftUI

iOS gives us several ways to read and write user data, and UserDefaults is one of them. UserDefaults allows us to store a small amount of user data directly attached to our app. There is no specific number attached to “small”, but you should keep in mind that everything you store in UserDefaults will automatically be loaded when your app launches – if you store a lot in there your app launch will slow down. To give you at least an idea, you should aim to store no more than 512KB in there.

@AppStorage Property Wrapper in SwiftUI

@AppStorage is a convenient way to save and read variables from UserDefaults and use them in the same way as @State properties. It can be seen as a @State property which is automatically saved to (and read from) UserDefaults.

Assume that we need to store the user’s name with UserDefaults. We declare a variable decorated by @AppStorage property wrapper with a key name, as below.

import SwiftUI

struct ContentView: View {
    
    @AppStorage("user.name") var name = ""
    
    var body: some View {
        Form {
            TextField("Name", text: $name)
        }
    }
}

Next, debug in a simulator, you can enter any words in the text field. Meanwhile, iOS saves the value in the text field.

Then, we terminate the app and run it again, you can found that the value you entered before is in the text field.

App launches at the first time
App launches at the second time

Notice that, user data stored in UserDefaults will be removed when the user removes the app. Therefore, if you want to persistence user’s data, you may need to save the user’s data remotely. In another word, UserDefaults is used to store local settings. For example, we save a string to identify whether a user accepts the privacy policy.

What for Big and Complex Data?

Alternatively, if you need to store “big” and “complex” data in the user’s device, Core Data may be a good choice. You can read other posts about Core Data for details as below.

Leave a Reply

Your email address will not be published. Required fields are marked *