Created
September 16, 2022 02:59
-
-
Save WillBishop/aa2790f89c7a9d713b6500187f4ab34c to your computer and use it in GitHub Desktop.
Using Images in Live Activities without exceeding 4kb limit
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
struct LiveActivityAttributes: ActivityAttributes { | |
typealias ContentState = LiveActivityState | |
struct LiveActivityState: Codable, Hashable { | |
var activityScore: Int | |
} | |
var activityName: String | |
var _image: UIImage? | |
weak var image: UIImage? { | |
guard let backgroundURL else { return nil } | |
return UIImage(contentsOfFile: backgroundURL.relativePath) | |
} | |
var backgroundURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.willbishop.BigPayloadLiveActivity")?.appending(path: "backgroundImage") | |
init(activityName: String, image: UIImage? = nil) { | |
self.activityName = activityName | |
self._image = image | |
} | |
enum CodingKeys: CodingKey { | |
case activityName | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: LiveActivityAttributes.CodingKeys.self) | |
try container.encode(self.activityName, forKey: .activityName) | |
//Encoding image to disk separately from Codable encode | |
guard let backgroundURL else { return } | |
guard let _image else { return } | |
guard let ciImage = _image.ciImage ?? CIImage(image: _image) else { return } | |
guard let reencodedImageData = UIImage(ciImage: ciImage).jpegData(compressionQuality: 0) else { return } | |
try? reencodedImageData.write(to: backgroundURL) | |
} | |
init(from decoder: Decoder) throws { | |
let container: KeyedDecodingContainer<LiveActivityAttributes.CodingKeys> = try decoder.container(keyedBy: LiveActivityAttributes.CodingKeys.self) | |
self.activityName = try container.decode(String.self, forKey: .activityName) | |
//We don't decode the image here as this causes a code 0/1 error in ActivityKit as the size becomes greater than 4kb. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment