Seungjun
Seungjun

Reputation: 984

How do I keep data in my app after it's closed at swiftUI?

I want to show same screen to user even after the user closed the app and re-opened it

The data I'm trying to save is just 3 state property, that's all.

How can I do it at swiftUI?

Upvotes: 2

Views: 4433

Answers (1)

Dan O'Leary
Dan O'Leary

Reputation: 946

If you're saving simple data I would recommend just using UserDefaults. I wrote a small app in SwiftUI to demonstrate the implementation of this, but hopefully you will be able to adapt the concepts to your needs.

You can see the process in action in the app if you put this code in a new project in Xcode. Enter the values then hit the "Save" button. Force-quit the app (but don't delete it) and relaunch the app. Pressing the "Load" button will reload the last saved values. You can save new values by pressing the Save button again.

If you want to load the saved values right when the screen/app appears just uncomment the line where you see .onAppear(perform: load).

I hope this helps! -Dan

import SwiftUI


struct ContentView: View {
@State private var isBirthday = false
@State private var age = ""
@State private var name = ""

private let defaults = UserDefaults.standard

var body: some View {
    VStack {
        Spacer()
        TextField("Enter your name", text: $name)
        TextField("Enter your age.", text: $age)
        Toggle(isOn: $isBirthday) {
            Text("Is it your birthday?")
        }.padding()
        Spacer()

        Text("\(name)")
        Text("\(age)")
        Text(isBirthday ? "Happy Birthday!" : "Hello \(name)")
        Spacer()
        HStack {
            Button("Save") {
                self.save()
            }
            .padding(30)
            .border(Color.blue)

            Button("Load") {
                self.load()
            }
            .padding(30)
            .border(Color.green)

        }
    }
//      .onAppear(perform: load)
    .textFieldStyle(RoundedBorderTextFieldStyle())
}

func save() {
    defaults.set(isBirthday, forKey: "birthday")
    defaults.set(age, forKey: "age")
    defaults.set(name, forKey: "name")
}

func load() {
    let savedName = defaults.string(forKey: "name")
    let savedAge = defaults.string(forKey: "age")
    let savedBirthday = defaults.bool(forKey: "birthday")

    isBirthday = savedBirthday
    // using nil coalescing operator as a guard for the optional values but there are other ways to handle this.
    age = savedAge ?? ""
    name = savedName ?? ""
  }
}



struct ContentView_Previews: PreviewProvider {
static var previews: some View {
    ContentView()
   }
}

Upvotes: 3

Related Questions