Today I am going to show how to download an image from URL and manage the image cache.
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. The opposite of lazy loading is eager loading.
Here I will show you an example where I will download and cached image in TableView.
Steps for lazy loading.
Step 1: Create an Image class where we will download an image and cached.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class ImageLoader { var task: URLSessionDownloadTask! var session: URLSession! var cache: NSCache<NSString, UIImage>! init() { session = URLSession.shared task = URLSessionDownloadTask() self.cache = NSCache() } func obtainImageWithPath(imagePath: String, completionHandler: @escaping (UIImage) -> ()) { if let image = self.cache.object(forKey: imagePath as NSString) { DispatchQueue.main.async { completionHandler(image) } } else { let placeholder = #imageLiteral(resourceName: "placeholder") DispatchQueue.main.async { completionHandler(placeholder) } let url: URL! = URL(string: imagePath) task = session.downloadTask(with: url, completionHandler: { (location, response, error) in if let data = try? Data(contentsOf: url) { let img: UIImage! = UIImage(data: data) self.cache.setObject(img, forKey: imagePath as NSString) DispatchQueue.main.async { completionHandler(img) } } }) task.resume() } } } |
Steps 2: Create an object for the ImageLoader class.
1 |
var imageLoader = ImageLoader() |
Step 3: Download images in cellForRowAt
1 2 3 4 5 6 7 8 9 |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier") imageLoader.obtainImageWithPath(imagePath: viewModel.image) { (image) in if let updateCell = tableView.cellForRow(at: indexPath) { updateCell.imageView.image = image } } return cell } |
Hope the above blog will help you to implement lazy loading in UITableview iOS using swift.