Skip to content

Instantly share code, notes, and snippets.

@isaac-weisberg
Last active June 15, 2022 22:30
Show Gist options
  • Save isaac-weisberg/c7cfa29176ee257d71c21581b98eb929 to your computer and use it in GitHub Desktop.
Save isaac-weisberg/c7cfa29176ee257d71c21581b98eb929 to your computer and use it in GitHub Desktop.
import UIKit
protocol IImageProvider: AnyObject {
func retrieve(_ completion: @escaping (UIImage?) -> Void)
func preload()
}
protocol IImageProviderConsumer {
var currentProvider: IImageProvider? { get set }
func apply(_ provider: IImageProvider)
func removeProvider()
}
var providerContext: UInt8 = 0
extension UIImageView: IImageProviderConsumer {
var currentProvider: IImageProvider? {
get {
let currentProviderRawObject = objc_getAssociatedObject(self, &providerContext)
guard let currentProviderRawObjectUnwrapped = currentProviderRawObject else {
return nil
}
let currentProvider = currentProviderRawObjectUnwrapped as! IImageProvider
return currentProvider
}
set {
objc_setAssociatedObject(self, &providerContext, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func apply(_ provider: IImageProvider) {
if provider !== currentProvider {
image = nil
}
self.currentProvider = provider
provider.retrieve { [weak self] image in
guard let self = self else { return }
guard self.currentProvider === provider else { return }
self.image = image
}
}
func removeProvider() {
currentProvider = nil
image = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment