Last active
June 15, 2022 22:30
-
-
Save isaac-weisberg/c7cfa29176ee257d71c21581b98eb929 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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