Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- typealias ImageCacheLoaderCompletionHandler = ((UIImage) -> ())
- class ImageCacheLoader {
- 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 ImageCacheLoaderCompletionHandler) {
- if let image = self.cache.object(forKey: imagePath as NSString) {
- DispatchQueue.main.async {
- completionHandler(image)
- }
- } else {
- /* You need placeholder image in your assets,
- if you want to display a placeholder to user */
- let placeholder = UIImage(bundleImageName: "Contact List/CreateGroupActionIcon")!
- DispatchQueue.main.async {
- completionHandler(placeholder)
- }
- let url: URL! = URL(string: imagePath)
- task = session.downloadTask(with: url, completionHandler: { (location, response, error) in
- if let location = location {
- if let data = try? Data(contentsOf: location) {
- let img: UIImage! = UIImage(data: data)
- self.cache.setObject(img, forKey: imagePath as NSString)
- DispatchQueue.main.async {
- completionHandler(img)
- }
- }
- }
- })
- task.resume()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment