Skip to content
Permalink
master
Go to file
1 contributor
75 lines (71 sloc) 2.62 KB
//
// UIImageView+loadFromUrl.swift
//
// Created by Sivabalaa Jothibose on 20/05/2020.
// Copyright © 2020 iOSTree. All rights reserved.
//
import UIKit
extension UIImageView {
//MARK:- Download image from URL
func setImage(from url: URL?, placeholder: UIImage? = nil, isCache: Bool = false) {
guard let loadURL = url else {
self.image = placeholder
return
}
//Cached image
if isCache {
UIImage.cacheImage(url: loadURL as NSURL) { (image) in
self.image = image
}
} else {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: loadURL) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}
}
private let cachedImages = NSCache<NSURL, UIImage>()
private var loadingResponses = [NSURL: [(UIImage?) -> Swift.Void]]()
extension UIImage {
// Returns the cached image if available, otherwise asynchronously loads and caches it.
static func cacheImage(url: NSURL, completion: @escaping (UIImage?) -> Swift.Void) {
// Check for a cached image.
if let cachedImage = cachedImages.object(forKey: url) {
completion(cachedImage)
return
}
// In case there are more than one requestor for the image, we append their completion block.
if loadingResponses[url] != nil {
loadingResponses[url]?.append(completion)
return
} else {
loadingResponses[url] = [completion]
}
// Go fetch the image.
URLSession(configuration: URLSessionConfiguration.ephemeral).dataTask(with: url as URL) { (data, response, error) in
// Check for the error, then data and try to create the image.
guard error == nil, let responseData = data, let image = UIImage(data: responseData),
let blocks = loadingResponses[url] else {
DispatchQueue.main.async {
completion(nil)
}
return
}
// Cache the image.
cachedImages.setObject(image, forKey: url, cost: responseData.count)
// Iterate over each requestor for the image and pass it back.
for block in blocks {
DispatchQueue.main.async {
block(image)
}
}
loadingResponses[url] = nil
}.resume()
}
}
You can’t perform that action at this time.