Skip to content

Instantly share code, notes, and snippets.

@Coder-ACJHP
Created December 19, 2018 11:17
Show Gist options
  • Save Coder-ACJHP/8fbb9991d5e34ba8de5126a7d94afa52 to your computer and use it in GitHub Desktop.
Save Coder-ACJHP/8fbb9991d5e34ba8de5126a7d94afa52 to your computer and use it in GitHub Desktop.
Modified image view that can cache and download images, first it will try fetch the image from cache if couldn't found it will download from the given url
//
// CachableImageView.swift
// Test
//
// Created by Coder ACJHP on 26.10.2018.
// Copyright © 2018 Coder ACJHP. All rights reserved.
//
import UIKit
// This extension allow us to download image from the url
let imageCache = NSCache<AnyObject, AnyObject>()
class CachableImageView: UIImageView {
var imageUrlString: String?
func loadImageUsingUrlString(urlString: String) {
let url = URL(string: urlString)!
self.image = nil
// If image already stored in cache assing it to image
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
// Download the image and store it in cache
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
return
}
DispatchQueue.main.async {
let imageToCache = UIImage(data: data!)
if self.imageUrlString == urlString {
self.image = imageToCache
}
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
}
}.resume()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment