优化图片缓存

This commit is contained in:
Fin 2025-06-04 09:41:55 +08:00
parent c1d9dfe7f6
commit 639e511c30

View File

@ -90,13 +90,9 @@ class MessageItemView: UIView {
var tapAction: ((_ message: MessageItemModel, _ sourceView: MessageItemView) -> Void)?
static var imageCache: ImageCache?
static var imageCacheCreatedTime: Date?
///
lazy var imageCache: ImageCache = {
let groupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bark")
let cache = try? ImageCache(name: "shared", cacheDirectoryURL: groupUrl)
return cache ?? KingfisherManager.shared.cache
}()
init() {
super.init(frame: .zero)
@ -163,6 +159,22 @@ class MessageItemView: UIView {
}
extension MessageItemView {
///
/// - Note: date Kingfisher/DiskStorage 使 maybeCached Set
/// Bark NotificationServiceExtension 使 ImageCache APP ImageCache maybeCached
/// - Parameter date:
/// - Returns:
func getImageCache(date: Date) -> ImageCache {
if let cache = MessageItemView.imageCache, let createdTime = MessageItemView.imageCacheCreatedTime, createdTime > date {
return cache
}
let groupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bark")
let cache = try? ImageCache(name: "shared", cacheDirectoryURL: groupUrl)
MessageItemView.imageCache = cache
MessageItemView.imageCacheCreatedTime = Date()
return cache ?? ImageCache.default
}
func setMessage(message: MessageItemModel) {
self.bodyLabel.attributedText = message.attributedText
self.dateLabel.text = message.dateText
@ -174,7 +186,7 @@ extension MessageItemView {
imageView.removeImageViewer()
// loadDiskFileSynchronously
imageView.kf.setImage(with: URL(string: image), options: [.targetCache(imageCache), .keepCurrentImageWhileLoading, .loadDiskFileSynchronously]) { [weak self] result in
imageView.kf.setImage(with: URL(string: image), options: [.targetCache(getImageCache(date: message.createDate ?? Date())), .keepCurrentImageWhileLoading, .loadDiskFileSynchronously]) { [weak self] result in
guard let self else { return }
guard let image = try? result.get().image else {
self.imageView.image = nil