Created
December 18, 2018 03:58
-
-
Save sarunw/12bde9e7cd90cc08d2454dd920db4de2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension KeyedEncodingContainer { | |
mutating func encode(_ value: UIImage, | |
forKey key: KeyedEncodingContainer.Key) throws { | |
let imageData = value.jpegData(compressionQuality: 1) | |
let prefix = "data:image/jpeg;base64," | |
guard let base64String = imageData?.base64EncodedString(options: .lineLength64Characters) else { | |
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "Can't encode image to base64 string.")) | |
} | |
try encode(prefix + base64String, forKey: key) | |
} | |
} | |
extension KeyedDecodingContainer { | |
public func decode(_ type: UIImage.Type, forKey key: KeyedDecodingContainer.Key) throws -> UIImage { | |
let base64String = try decode(String.self, forKey: key) | |
// data:image/svg+xml;base64,PD..... | |
let components = base64String.split(separator: ",") | |
if components.count != 2 { | |
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Unsupported format")) | |
} | |
let dataString = String(components[1]) | |
if let dataDecoded = Data(base64Encoded: dataString, options: .ignoreUnknownCharacters), let image = UIImage(data: dataDecoded) { | |
return image | |
} else { | |
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Unsupported format")) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment