How can make Codable of type PhotosPickerItem?

94 views Asked by At

I'm trying to save an array like PhotosPickerItem (instead of an array of images to save memory) in any available form, for example, through UserDefaults using Codable. However, I can't match the specified type with the Codable protocol, or convert PhotosPickerItem to Data. Also, when I try to use NSObject, NSCoding protocols, an encoding error is displayed when running the code. I would be grateful for advice and code example, as I did not find a suitable option (there are only examples with the String and Int type).

// example of Code

import SwiftUI
import PhotosUI

struct PickerItem: Codable {
    var selectedPickerItem: PhotosPickerItem  // **this is not correct (only simple type like String or Int is correct)**

struct PickerItemManager {
    
    static let defaults = UserDefaults.standard
    private init(){}
    
    // save Data method
    static func savePickerItems(pickerItem: [PickerItem]) {
        do {
            let encoder = JSONEncoder()
            let pickerItems = try encoder.encode(pickerItem)
            defaults.setValue(pickerItems, forKey: "pickerKeyName")
        } catch let error {
            print(#function, error)
        }
    }
    
    //retrieve data method
    static func getPickerItems() -> [PickerItem]{
        
        guard let pickerItemsData = defaults.object(forKey: "pickerKeyName") as? Data else {return []}
        do{
            let decoder = JSONDecoder()
            let pickerItems = try decoder.decode([PickerItem].self, from: pickerItemsData)
            return pickerItems
        } catch let error {
            return([])
        }
    }
}
0

There are 0 answers