In this post, we’ll explore how to use AppStorage. Commonly, UserDefaults is employed to save small amounts of data, such as user preferences in an app. However, it comes with certain limitations:
- The data is saved in a single .plist file, indicating that having a large file is not the optimal solution. On Apple TV, there is a fixed limit of 1 MB, but it’s recommended to keep the file size smaller, particularly if these default values are loaded at app startup for speed considerations.
- The data is stored in plaintext, so it’s NOT suitable for sensitive information.
- The permitted types are: Data, String, Date, Bool, Int, Double, Float, Array, Dictionary, and URL.
What is AppStorage? It’s a wrapper for UserDefaults that allows us to save and load data from UserDefaults without having to directly call it.
Take a look at a short example:
struct ContentView: View { @AppStorage("enabled") private var enabled = false @AppStorage("nickname") private var nickname = "" var body: some View { VStack { Form { TextField("Nickname", text: $nickname) Toggle(isOn: $enabled) { Text("Enable") } } } .padding() } }
So, we declare the variable with @AppStorage and use it similarly to how we use @State variables. The primary difference is that, in this case, the changes are automatically saved (and loaded).
Simple and powerful. That’all.