Search code examples
iosswiftuserdefaults

How to save data in userdefaults when is from a model


I have a Model like this

struct House: Codable {
    let address: String?
    let rooms: String?
    let garage: Garage
}

struct Garage: Codable {
    let space: String?
    let numbers_of_ cars: String?
}

I get from a api the data and set to can show it, now I need to save in userdefaults to can show info if there is not any network o wifi

I am trying like this

var itemItems = [House]()

fileprivate func fetchData() {
        Service.shared.fetchCourses { (houses, err) in
            if let err = err {
                print("Failed to fetch houses:", err)
                return
            }

        self.itemItems = houses!

        var itemsToSave = [House]()
        for i in 0..<self.itemItems.count {
            itemsToSave.append(self.itemItems[i])
        }

        UserDefaults.standard.set(arrayToSave, forKey : "arrayToSave")

        }
    }

but!! I get an error check the image

https://i.ibb.co/bHhtj28/Captura-de-Pantalla-2019-11-24-a-la-s-4-25-18-p-m.png


Solution

  • You cannot save custom structs to UserDefaults directly.

    But as both structs conform to Codable encode them

    var itemItems = [House]()
    
    fileprivate func fetchData() {
        Service.shared.fetchCourses { (houses, err) in
            if let err = err {
                print("Failed to fetch houses:", err)
                return
            }
    
            self.itemItems = houses!
            do {
               let data = try JSONEncoder().encode(self.itemItems)
               UserDefaults.standard.set(data, forKey : "houses")
            } catch { print(error) }      
        }
    }