Using AppStorage to Store and Access User Defaults in SwiftUI
WWDC20 introduced AppStorage, a new property wrapper around UserDefaults that lets you write and read from UserDefaults more easily. Read the section about UserDefaults to learn more about it. In this section, let's learn how to set a new UserDefaults variable using AppStorage, how to read from it and how to change a variable in AppStorage.
Use the newly introduced AppStorage to add to UserDefaults.
Set a variable in UserDefaults
To create a new variable in UserDefaults and set its initial value, simply call the AppStorage wrapper and set your initial value directly:
@AppStorage("themePreference") var themePreference: String = "dark"
..
Read from UserDefaults
To read the themePreference variable in UserDefaults, you just need to call the themePreference variable:
Text("Your theme preference is: \(themePreference).")
..
Write to UserDefaults
To change a variable, simply assign it a new value:
Button("Change theme preference to light") {
themePreference = "light"
}
..
Notes
- In conclusion, AppStorage is a new wrapper introduced at WWDC20 and makes it easier to write and read from UserDefaults, as well as makes the code cleaner to read.
- Remember to not store too much data in the AppStorage and to not store sensitive information in it as it is not very secure and easily hackable.
import SwiftUI
struct ContentView: View {
@AppStorage("username") var username = "JohnDoe"
@AppStorage("isDarkModeOn") var isDarkModeOn = false
var body: some View {
VStack {
Text("Username: \(username)")
.padding()
Toggle(isOn: $isDarkModeOn) {
Text("Dark Mode")
}
.padding()
}
.preferredColorScheme(isDarkModeOn ? .dark : .light)
}
}
Comments
Post a Comment