Permalink
Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upUIImageView-loadFromUrl/UIImageView+loadFromUrl.swift
Go to file// | |
// 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() | |
} | |
} |