Guest User

Untitled

a guest
Feb 12th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.59 KB | None | 0 0
  1. typealias ImageCacheLoaderCompletionHandler = ((UIImage) -> ())
  2.  
  3. class ImageCacheLoader {
  4.  
  5.     var task: URLSessionDownloadTask!
  6.     var session: URLSession!
  7.     var cache: NSCache<NSString, UIImage>!
  8.  
  9.     init() {
  10.         session = URLSession.shared
  11.         task = URLSessionDownloadTask()
  12.         self.cache = NSCache()
  13.     }
  14.  
  15.     func obtainImageWithPath(imagePath: String, completionHandler: @escaping ImageCacheLoaderCompletionHandler) {
  16.         if let image = self.cache.object(forKey: imagePath as NSString) {
  17.             DispatchQueue.main.async {
  18.                 completionHandler(image)
  19.             }
  20.         } else {
  21.             /* You need placeholder image in your assets,
  22.                if you want to display a placeholder to user */
  23.             let placeholder = UIImage(bundleImageName: "Contact List/CreateGroupActionIcon")!
  24.             DispatchQueue.main.async {
  25.                 completionHandler(placeholder)
  26.             }
  27.             let url: URL! = URL(string: imagePath)
  28.             task = session.downloadTask(with: url, completionHandler: { (location, response, error) in
  29.                 if let location = location {
  30.                     if let data = try? Data(contentsOf: location) {
  31.                         let img: UIImage! = UIImage(data: data)
  32.                         self.cache.setObject(img, forKey: imagePath as NSString)
  33.                         DispatchQueue.main.async {
  34.                             completionHandler(img)
  35.                         }
  36.                     }
  37.                 }
  38.             })
  39.             task.resume()
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment