Tusker/Tusker/Views/CachedImageView.swift

65 lines
1.6 KiB
Swift
Raw Normal View History

2022-10-05 21:40:00 +00:00
//
// CachedImageView.swift
// Tusker
//
// Created by Shadowfacts on 10/4/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
class CachedImageView: UIImageView {
private let cache: ImageCache
private var url: URL?
private var isGrayscale = false
private var fetchTask: Task<Void, Error>?
init(cache: ImageCache) {
self.cache = cache
super.init(frame: .zero)
NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(for url: URL?) {
if url != self.url {
self.url = url
updateImage()
}
}
@objc private func preferencesChanged() {
if isGrayscale != Preferences.shared.grayscaleImages {
updateImage()
}
}
private func updateImage() {
fetchTask?.cancel()
fetchTask = Task(priority: .high) {
self.image = nil
guard let url else {
return
}
let (_, image) = await cache.get(url)
guard let image else {
return
}
try Task.checkCancellation()
// TODO: check that this isn't on the main thread
guard let transformedImage = ImageGrayscalifier.convertIfNecessary(url: url, image: image) else {
return
}
try Task.checkCancellation()
2022-10-05 21:40:00 +00:00
self.image = transformedImage
}
}
}