article

Wednesday, September 8, 2021

SwiftUI How to Store Data using User Defaults

SwiftUI How to Store Data using User Defaults

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var msg = ""
    @State var retrived = ""
    
    var body: some View {
        
        VStack {
            
            Text(retrived).fontWeight(.heavy)
            
            TextField("Enter msg to Save", text: $msg)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            
            Button (action: {
                UserDefaults.standard.set(self.msg, forKey: "Msg")
                self.retrived = self.msg
                self.msg = ""
            }) {
                Text("Save").padding()
            }.background(Color.orange)
            .foregroundColor(.white)
            .cornerRadius(9)
        }
        .onAppear {

            guard let retreivedmsg = UserDefaults.standard.value(forKey: "Msg") else { return }
            
            self.retrived = retreivedmsg as! String
        }
    }
}

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

Related Post