Persisting Data in UserDefaults Using SwiftUI

azamsharp · 5K views · 2019 · 8:27

Open on YouTube

Software (other)Web developmenttutorialdated

Why Stack Overflow recommends it

Stack Overflow users link it when answering how to bind SwiftUI controls like Toggle and TextField to UserDefaults, and several adapt its ObservableObject pattern directly.

Recommended by 1 people across 1 different months, 2019 to 2020.

What it is

A short screencast by Mohammad Azam (azamsharp) showing how to persist data to UserDefaults in a SwiftUI app. It uses an ObservableObject with @Published properties whose didSet writes to UserDefaults, bound to a Toggle in the view.

What people said

Recommends protasm · 2019-10 · Stack Overflow · on “How do I use UserDefaults with SwiftUI?”

The code below adapts Mohammad Azam's excellent solution in this video [this video] : import SwiftUI struct ContentView: View { @ObservedObject var userDefaultsManager = UserDefaultsManager() var body: some View { VStack { Toggle(isOn: self.$userDefaultsManager.firstToggle) { Text("First Toggle") } Toggle(isOn: self.$userDefaultsManager.secondToggle) { Text("Second Toggle") } } } } class UserDefaultsManager: ObservableObject { @Published var firstToggle: Bool = UserDefaults.standard.bool(forKey: "firstToggle") { didSet { UserDefaults.standard.set(self.firstToggle, forKey: "firstToggle") } } @Published var secondToggle: Bool = UserDefaults.standard.bool(forKey: "secondToggle") { didSet { UserDefau

Cites oscar · 2019-09 · Stack Overflow · on “Save string from TextField in UserDefaults with SwiftUI”

How can the string from a TextField be stored in UserDefaults using SwiftUI ? I have seen this tutorial on how to save the state of a toggle in UserDefaults and that looks promising, but I can't figure out how to use the same idea for storing the content from a TextField: [this video] I still want to be able to update the string by typing new text in the TextField, but unless I do that, I want the string to be maintained in the view. Both when changing page and completely exitting the app.

Cites esedege · 2020-02 · Stack Overflow · on “UserDefaults Binding with Toggle in SwiftUI”

With help both from this video by azamsharp [this video] and this tutorial by Paul Hudson [LINK] , I've been able to produce a toggle that binds to UserDefaults and shows whichever change you've assigned to it instantaneously. Scene Delegate: Add this line of code under 'window' variable var settingsStore = SettingsStore() And modify window.rootViewController to show this window.rootViewController = UIHostingController(rootView: contentView.environmentObject(settingsStore)) SettingsStore: import Foundation class SettingsStore: ObservableObject { @Published var isOn: Bool = UserDefaults.standard.bool(forKey: "isOn") { didSet { UserDefaults.standard.set(self.isOn, forKey: "isOn") } } } SettingsStor