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
}
}
The line
cannot work because casting
ArraytoSetwill always fail. Replace the line withand use the same syntax in
getDataFromUserDefaults