how can add data from user defaults to next view in swiftui on button press

75 Views Asked by At

I was add the user defaults to my struct ,I want to add the product from product list screen to favourite screen when press the heart button and also want to remove when button press again, here my favouritedData is showing empty, what did I do for getting the stored values from userdefaults to favourite view

class FavouriteViewModel : ObservableObject {
        @Published var isfavourite = false
        @Published var productData = Set<ProductData>()
        // the products which user marked as favourites
        @Published var favourites : Set<Int>
        let defaults = UserDefaults.standard
         var favItems : [ProductData] = []
        init() {
          // save and load data in Userdefaults
            let decoder = PropertyListDecoder()
           if let data = defaults.data(forKey: "ProductItem") {
               productData = (try? decoder.decode(Set<ProductData>.self, from: data) ) ?? Set(favItems)
           } else {
               productData = Set(favItems)
           }
            self.favourites = Set(defaults.array(forKey: "Favourites") as? Set<Int> ?? [])
             getDataFromUserDefaults()
            
        }
        func getIds() -> Set<Int> {
            return favourites
        }
        func contains(productItem:ProductData) -> Bool {
            favourites.contains(productItem.id)
        }
        func addToFav(productItem:ProductData) {
            favourites.insert(productItem.id)
            save()
        }
        func removeFromFav(productItem:ProductData) {
            favourites.remove(productItem.id)
            save()
        }
        func save() {
            // save/write data
            let encoder = PropertyListEncoder()
            if let encoded = try? encoder.encode(self.productData) {
                self.defaults.set(encoded, forKey: "ProductItem")
            }
            self.defaults.set(Array(self.favourites), forKey: "Favourites")
            
        }
        
        func getDataFromUserDefaults() {
            let favouritedData = defaults.object(forKey: "Favourites") as? Set<Int> ?? []
            print("the favourited data is \(favouritedData)")
        }
    }

This is my model:-

struct ProductModel : Decodable {
    let productData : [ProductData]
    
    private enum CodingKeys:String,CodingKey {
        case productData = "data"
    }
}

struct ProductData : Identifiable,Decodable,Hashable {
    var id : Int
    var title :String
    var type : String
    var description : String
    var filename : String
    var price : Float
    var rating : Int
    
    init() {
        self.id = 0
        self.title = ""
        self.type = ""
        self.description = ""
        self.filename = ""
        self.price = 0.0
        self.rating = 0
    }
   
}
1

There are 1 best solutions below

0
vadian On

The line

self.favourites = Set(defaults.array(forKey: "Favourites") as? Set<Int> ?? [])

cannot work because casting Array to Set will always fail. Replace the line with

self.favourites = Set(defaults.array(forKey: "Favourites") as? [Int] ?? [])

and use the same syntax in getDataFromUserDefaults

 let favouritedData = Set(defaults.array(forKey: "Favourites") as? [Int] ?? [])