Tuesday, March 5, 2024
HomeiOS Developmentios - View not reflecting knowledge coming from Consumer Defaults

ios – View not reflecting knowledge coming from Consumer Defaults


I’ve created a singleton class referred to as AppSecurityStore which at present solely holds a boolean property to retailer a setting worth.

remaining class AppSecurityStore {
    static let shared = AppSecurityStore()
    
    personal init() { }
    
    var isAppLockEnabled: Bool {
        get {
            UserDefaults.customary.bool(forKey: "AppLock")
        }
        set {
            UserDefaults.customary.setValue(newValue, forKey: "AppLock")
        }
    }
}

I’ve a view the place I toggle the worth for this property.

struct ContentView: View {
    @State personal var appSecurityStore: AppSecurityStore
    
    init(appSecurityStore: AppSecurityStore) {
        self.appSecurityStore = appSecurityStore
    }
    
    var physique: some View {
        Type {
            Part {
                Toggle("App Lock", isOn: $appSecurityStore.isAppLockEnabled)
            }
        }
    }
}

If I modify the toggle worth, it does get saved in Consumer Defaults correctly. Nevertheless if I background the app and convey it again to the foreground, it does not mirror the up to date state. It nonetheless reveals the earlier worth!

Gif demonstrating the difficulty

The appSecurityStore variable contained in the view is a @State variable so I am unsure why it does not persist the up to date worth.

Any assist to resolve that is appreciated.

I’ve uploaded a demo challenge right here.

Necessary: I can not use surroundings objects on this app because of selections being made to not use them since they do not play properly with MVVM.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments