How to set custom class array data in UserDefalts in swift 4

34 Views Asked by At

I have A Array List

private var deviceArray: [SearchPeripheral]? = []

I want to hold data of device array in UserDefaults but its crashing when I store it. please help me on it

Thank you.

1

There are 1 best solutions below

0
On

You can't store custom models in UserDefaults. You can make the following improvements to save your objects as [[String:Any]]

struct SearchPeripheral: Codable {
    let name: String
    let model: String
}

extension SearchPeripheral {
    var dictionary: [String:Any] {
        let data = try! JSONEncoder().encode(self)
        let any = try! JSONSerialization.jsonObject(with: data)
        return any as! [String:Any]
    }

    init?(_ dict: [String:Any]) {
        guard let peripheral = (try? JSONSerialization.data(withJSONObject: dict)).flatMap({
            try? JSONDecoder().decode(SearchPeripheral.self, from: $0)
        }) else {
            return nil
        }
    
        self = peripheral
    }
}

Saving Array of SearchPeripheral:

func save(_ peripherals: [SearchPeripheral]) {
    let allPeripherals = peripherals.compactMap({$0.dictionary})
    UserDefaults.standard.set(allPeripherals, forKey: "peripherals")
}

Getting Array of SearchPeripherals:

func getPeripherals() -> [SearchPeripheral] {
    let allPeripherals = UserDefaults.standard.array(forKey: "peripherals") as? [[String:Any]] ?? []
    let peripherals = allPeripherals.compactMap(SearchPeripheral.init)
    return peripherals
}