Created
September 3, 2019 04:44
-
-
Save mjhassan/6ee370ece0de796c3bc88ac3d7a1ed0e to your computer and use it in GitHub Desktop.
Simple custom image view to load image asynchronously, uses URLCache
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
| class UIAsyncImageView: UIImageView { | |
| // Associated Object property; implementation omitted. | |
| final private var imageUrl: URL? | |
| func loadImage(from urlString: String, placeholder: UIImage? = nil) { | |
| setImage(placeholder) | |
| guard let url = URL(string: urlString) else { | |
| return | |
| } | |
| imageUrl = url | |
| APIService().get(url: url) { [weak self] (data, error) in | |
| guard let _imageUrl = self?.imageUrl, _imageUrl == url else { | |
| return | |
| } | |
| guard let data = data, let image = UIImage(data: data) else { | |
| return | |
| } | |
| self?.setImage(image) | |
| } | |
| } | |
| private func setImage(_ image: UIImage?) { | |
| DispatchQueue.main.async { [weak self] in | |
| self?.image = image | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment