Skip to content

Instantly share code, notes, and snippets.

@Zhendryk
Created November 1, 2018 19:25
Show Gist options
  • Save Zhendryk/b27142b0127ba818d48e8ee4547ea7c1 to your computer and use it in GitHub Desktop.
Save Zhendryk/b27142b0127ba818d48e8ee4547ea7c1 to your computer and use it in GitHub Desktop.
Allows a user to download an image asynchronously directly into a UIImageView and cache it
//
// UIImageView+asyncCache.swift
//
// Created by Zhendryk on 10/18/18.
// Copyright © 2018 Zhendryk. All rights reserved.
import Foundation
import UIKit
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func getImageFrom(urlString: String?, contentMode: UIView.ContentMode = .scaleAspectFit, placeholder: UIImage? = nil) {
if urlString == nil {
self.image = placeholder
return
}
self.image = placeholder
self.contentMode = contentMode
if let cachedImage = imageCache.object(forKey: NSString(string: urlString!)) {
self.image = cachedImage
return
}
if let url = URL(string: urlString!) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
AppUtil.debugLog(file: #file, function: #function, line: #line, error)
DispatchQueue.main.async {
self.image = placeholder
}
return
}
DispatchQueue.main.async {
if let data = data {
if let downloadedImage = UIImage(data: data) {
imageCache.setObject(downloadedImage, forKey: NSString(string: urlString!))
self.image = downloadedImage
self.layoutSubviews()
}
}
}
}.resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment