I have a problem here. I have an array with custom objects, that contain pictures. When i install my app to my phone all pictures are at their place, but when i try to save changes to my array with UserDefaults - all is saving, except pictures. I have found tha the problem is with decoding pictures. They all change to placeholder picture. Can anybody help me and say whats wrong?
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
englishWord = try container.decode(String.self, forKey: .englishWord)
belarusianWord = try container.decodeIfPresent(String.self, forKey: .belarusianWord) ?? ""
englishDefinition = try container.decodeIfPresent(String.self, forKey: .englishDefinition) ?? ""
belarusianDefinition = try container.decodeIfPresent(String.self, forKey: .belarusianDefinition) ?? ""
let data = try container.decodeIfPresent(Data.self, forKey: CodingKeys.wordImage)
if let data = data {
guard let wordImage = UIImage(data: data) else {
throw NSError(domain: "Error decoding logo", code: 0, userInfo: nil)
}
self.wordImage = wordImage
} else {
wordImage = UIImage(named: "placeholder")!
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let data = UIImage().pngData()
try container.encode(data, forKey: CodingKeys.wordImage)
try container.encode(self.englishWord, forKey: .englishWord)
try container.encode(self.belarusianWord, forKey: .belarusianWord)
try container.encode(self.englishDefinition, forKey: .englishDefinition)
try container.encode(self.belarusianDefinition, forKey: .belarusianDefinition)
}
In encode(to:)
method, simply replace
let data = UIImage().pngData()
with
let data = self.wordImage.pngData()