Created
November 13, 2025 09:04
-
-
Save dterekhov/2f8bb70037ee5b420092d99f7c5d8688 to your computer and use it in GitHub Desktop.
KeyedCodingContainer+UIImage: UImage support for KeyedEncodingContainer #uikit #persistence #swift-api #real-project
This file contains hidden or 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
| import UIKit.UIImage | |
| public enum ImageEncodingQuality: CGFloat { | |
| case png = 0 | |
| case jpegLow = 0.2 | |
| case jpegMid = 0.5 | |
| case jpegHigh = 0.75 | |
| } | |
| public extension KeyedEncodingContainer { | |
| mutating func encode(_ value: UIImage, | |
| forKey key: KeyedEncodingContainer.Key, | |
| quality: ImageEncodingQuality = .png) throws { | |
| var imageData: Data! | |
| switch quality { | |
| case .png: | |
| imageData = value.pngData() | |
| case .jpegLow, | |
| .jpegMid, | |
| .jpegHigh: | |
| imageData = value.jpegData(compressionQuality: quality.rawValue) | |
| } | |
| try encode(imageData, forKey: key) | |
| } | |
| } | |
| public extension KeyedDecodingContainer { | |
| func decode(_ type: UIImage.Type, forKey key: KeyedDecodingContainer.Key) throws -> UIImage { | |
| let imageData = try decode(Data.self, forKey: key) | |
| if let image = UIImage(data: imageData) { | |
| return image | |
| } else { | |
| throw NSError(domain: Bundle.main.bundleIdentifier ?? "YourAppName", code: 0, userInfo: nil) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment