One of the best ways to reuse image data that you have already downloaded from network is image caching.
By applying image caching, you can prevent slow app performance such as lagging.
class GFAvatarImageView: UIImageView {
static let cache = NSCache<NSString, UIImage>()
}
func downloadImage(from urlString: String) {
let cacheKey = NSString(string: urlString)
if let image = GFAvatarImageView.cache.object(forKey: cacheKey){
self.image = image
return
}
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) {[weak self] data, response, error in
if let _ = error{ return }
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { return }
guard let data = data else { return }
guard let image = UIImage(data: data) else { return }
GFAvatarImageView.cache.setObject(image, forKey: cacheKey)
DispatchQueue.main.async {
self?.image = image
}
}.resume()
}
'Programming > Swift' 카테고리의 다른 글
[Readable Coding Practice] Show and dismiss loading signals (0) | 2021.06.19 |
---|---|
[Readable Coding Practice] UIScrollView Pagination (0) | 2021.06.19 |
[Readable Coding Practice] Fetching data from REST API with URLSession (0) | 2021.06.18 |
How to setup UITabBar programmatically (0) | 2021.06.06 |
Adrenalist does not collect any personal information (0) | 2021.05.06 |