1 min readJun 23, 2020
How to use AppStorage Property to communicate with UserDefaults and update SwiftUI view. New in iOS 14…
struct ContentView: View {
@AppStorage("notificationsOn") var notificationsOn: Bool = false
var body: some View {
VStack {
Toggle(isOn: $notificationsOn){
Text("Notifications ON")
}.padding()
Text("Notifications \(notificationsOn ? "ON" : "OFF")")
}
}
}
Toggling value of notificationsOn
will cause boolean value directly to be written to UserDefaults
Changes in UserDefaults for the property notificationsOn
would invalidate body and triggers view update.
Note: By default AppStorage utilizes standard user defaults, we can use alternate initializer to specify different user defaults if needed.
init(_ key: String, store: UserDefaults? = nil) where Value == Int?
i.e.
@AppStorage("notificationsOn", UserDefaults(suiteName: "com.app.settings")) var notificationsOn: Bool = false
Note: AppStorage Property Wrapper is released as part of SwiftUI framework.