Home > Software design >  Updating @Published var if a userdefault value is present swift
Updating @Published var if a userdefault value is present swift

Time:05-14

I am trying to check my app and see if a value exists in user defaults and if it does exist they will be taken into the app. If it doesnt exist they need to enter there pin and then get into the app.

Any idea how to check if a value is present in user defaults and then change isValidated to true

// main

import SwiftUI
@main
struct ProjectHogtieApp: App {
    @StateObject var authentication = Authentication()
    var body: some Scene {
        WindowGroup {
            if authentication.isValidated {
                ContentView()
                    .environmentObject(authentication)
            } else {
                LoginView()
                    .environmentObject(authentication)
            } 
        }
    }
}

// authentiction.swift

class Authentication: ObservableObject {
    
    @Published var isValidated = false
    
    // this code is not working.
    var getIsValidated: Void {
        let deviceId = UserDefaults.standard.string(forKey: "deviceId")
        if (deviceId != nil) {
            self.isValidated = true
        } else {
            self.isValidated = false
        }
    }

When the user enters there pin, I save the value in user defaults as shown below

let defaults = UserDefaults.standard
defaults.set(deviceId, forKey: "deviceId")

CodePudding user response:

try this, to check your UserDefaults when the App starts (ie. when Authentication is created):

class Authentication: ObservableObject {
    
    @Published var isValidated = false
    
    // --- here
    init() {
        getIsValidated
    }
  //....

Note that for important things like authentication etc... you should be using Keychain to save data securely, not UserDefaults

CodePudding user response:

You can continue down the path you're going. However, there exists a property wrapper in SwiftUI known as AppStorage. This is essentially a convenience wrapper to get and set values in UserDefaults. In this case, you might use it like this...

import SwiftUI

@main
struct ProjectHogtieApp: App {

    @AppStorage("isAuthenticated") private var isAuthenticated: Bool = false

    var body: some Scene {
        WindowGroup {
            if isAuthenticated {
                ContentView()
            } else {
                LoginView()
            } 
        }
    }
}

The parameter taken by the property wrapper is your key, and the value you provide is the default value, but will be overwritten by any existing value in UserDefaults.

  • Related