Created
November 1, 2018 19:25
-
-
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
This file contains 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
// | |
// 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