Swift 4 has Codable and it\'s awesome. But UIImage does not conform to it by default. How can we do that?
I tried with singleValueContainer
One way to pass an UIImage is to convert it to something that conforms to Codable, like String.
To convert the UIImage to String inside func encode(to encoder: Encoder) throws:
let imageData: Data = UIImagePNGRepresentation(image)!
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
try container.encode(strBase64, forKey: .image)
To convert the String back to UIImage inside required init(from decoder: Decoder) throws:
let strBase64: String = try values.decode(String.self, forKey: .image)
let dataDecoded: Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
image = UIImage(data: dataDecoded)