How to conform UIImage to Codable?

后端 未结 4 851
长发绾君心
长发绾君心 2020-12-09 02:28

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

4条回答
  •  忘掉有多难
    2020-12-09 03:03

    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)
    

提交回复
热议问题