Created
April 10, 2021 05:58
-
-
Save janeshsutharios/42d6fdcae3dbd332be60931c513eb784 to your computer and use it in GitHub Desktop.
UIIMageView+WithLoader
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
let imageCache = NSCache<NSString, UIImage>() | |
extension UIImageView { | |
func loadImageUsingCache(withUrl urlString : String) { | |
let url = URL(string: urlString) | |
if url == nil {return} | |
self.image = nil | |
if let cachedImage = imageCache.object(forKey: urlString as NSString) { | |
self.image = cachedImage | |
return | |
} | |
let indicatorView: UIActivityIndicatorView = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.medium) | |
indicatorView.translatesAutoresizingMaskIntoConstraints = false | |
addSubview(indicatorView) | |
let horizontalConstraint = NSLayoutConstraint(item: indicatorView, | |
attribute: .centerX, | |
relatedBy: .equal, | |
toItem: self, | |
attribute: .centerX, | |
multiplier: 1, | |
constant: 0) | |
let verticalConstraint = NSLayoutConstraint(item: indicatorView, | |
attribute: .centerY, | |
relatedBy: .equal, | |
toItem: self, | |
attribute: .centerY, | |
multiplier: 1, | |
constant: 0) | |
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint]) | |
indicatorView.startAnimating() | |
// if not, download image from url | |
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in | |
if error != nil { | |
print(error!) | |
return | |
} | |
DispatchQueue.main.async { | |
if let image = UIImage(data: data!) { | |
imageCache.setObject(image, forKey: urlString as NSString) | |
self.image = image | |
indicatorView.removeFromSuperview() | |
} | |
} | |
}).resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment