Swift Codable protocol… encoding / decoding NSCoding classes -
i have following struct…
struct photo: codable { let hasshadow: bool let image: uiimage? enum codingkeys: string, codingkey { case `self`, hasshadow, image } init(hasshadow: bool, image: uiimage?) { self.hasshadow = hasshadow self.image = image } init(from decoder: decoder) throws { let container = try decoder.container(keyedby: codingkeys.self) hasshadow = try container.decode(bool.self, forkey: .hasshadow) // fails image = try container.decode(uiimage?.self, forkey: .image) } func encode(to encoder: encoder) throws { var container = encoder.container(keyedby: codingkeys.self) try container.encode(hasshadow, forkey: .hasshadow) // fails try container.encode(image, forkey: .image) } } encoding photo fails …
optional not conform encodable because uiimage not conform encodable
decoding fails with…
key not found when expecting non-optional type optional coding key \"image\""))
is there way encode swift objects include nsobject subclass properties conform nscoding (uiimage, uicolor, etc)?
thanks @vadian pointing me in direction of encoding/decoding data…
class photo: codable { let hasshadow: bool let image: uiimage? enum codingkeys: string, codingkey { case `self`, hasshadow, imagedata } init(hasshadow: bool, image: uiimage?) { self.hasshadow = hasshadow self.image = image } required init(from decoder: decoder) throws { let container = try decoder.container(keyedby: codingkeys.self) hasshadow = try container.decode(bool.self, forkey: .hasshadow) if let imagedata = try container.decodeifpresent(data.self, forkey: .imagedata) { image = nskeyedunarchiver.unarchiveobject(with: imagedata) as? uiimage } else { image = nil } } func encode(to encoder: encoder) throws { var container = encoder.container(keyedby: codingkeys.self) try container.encode(hasshadow, forkey: .hasshadow) if let image = image { let imagedata = nskeyedarchiver.archiveddata(withrootobject: image) try container.encode(imagedata, forkey: .imagedata) } } }
Comments
Post a Comment