Guest User

Untitled

a guest
Dec 10th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. //
  2. // UIImageView+Extensions.swift
  3. // GT_PhotoAlbums
  4. //
  5. // Created by Leonid Nifantyev on 11/24/18.
  6. // Copyright © 2018 Leonid Nifantyev. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. final class CustomKey : NSObject {
  12. let string: String
  13.  
  14. init(string: String) {
  15. self.string = string
  16. }
  17.  
  18. override func isEqual(_ object: Any?) -> Bool {
  19. guard let other = object as? CustomKey else {
  20. return false
  21. }
  22. return string == other.string
  23. }
  24.  
  25. override var hash: Int {
  26. return string.hashValue
  27. }
  28. }
  29.  
  30. let imageCashe = NSCache<CustomKey, UIImage>()
  31.  
  32. extension UIImageView {
  33. func downloadImage(for urlString: String) {
  34.  
  35. image = nil
  36.  
  37. if let imageFromCashe = imageCashe.object(forKey: CustomKey(string: urlString)) {
  38. self.image = imageFromCashe
  39. return
  40. }
  41.  
  42. let url = URL(string: urlString)!
  43.  
  44. URLSession.shared.dataTask(with: url) { (data, responce, error) in
  45. guard error == nil else {
  46. return
  47. }
  48.  
  49. DispatchQueue.main.async {
  50.  
  51. let imageToCashe = UIImage(data: data!)
  52. imageCashe.setObject(imageToCashe!, forKey: CustomKey(string: urlString))
  53.  
  54. self.image = imageToCashe
  55. }
  56.  
  57. }.resume()
  58. }
  59. }
Add Comment
Please, Sign In to add comment