How to use UserData Observable Object in SwiftUI?

Viewed 406

In an Xcode SwiftUI project, I have a TextField in which user write the username.

I want that the username will be kept in memory when the user close the app.

So, I created a UserData.swift in which there are utilisateur and a boolean var :

final class UserData: ObservableObject  {
    @Published var utilisateur = ""
    @Published var connected = false
}

On my ContentView, I wrote this:

@EnvironmentObject var userData: UserData

and in the code, for each case I wrote one of these 3 possibilities.

self.userData.utilisateur
userData.utilisateur
userData.$utilisateur

Moreover, in SceneDelegate.swift, I wrote this :

window.rootViewController = UIHostingController(rootView: contentView.environmentObject(UserData()))

The problem is that when I close the app, the utilisateur value is deleted and not kept in memory.

Does someone know where is my mistake and what should I do to correct it?

1 Answers

Your UserData is not saved on disk. It remains in the memory but when you close your application it's gone. One way is to persist your data with UserDefaults:

//save
UserDefaults.standard.set(connected, forKey: "connected")

//read
let connected = UserDefaults.standard.bool(forKey: "connected")

You can find more information here:

To integrate it with your existing code you can use didSet on your @Published properties:

final class UserData: ObservableObject  {
    @Published var connected: Bool {
        didSet {
            UserDefaults.standard.set(connected, forKey: "connected")
        }
    }

    init() {
        _connected = .init(initialValue: UserDefaults.standard.bool(forKey: "connected"))
    }
}
Related