LLCache.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // LLCache.swift
  3. // LiveLikeGiphyChallenge
  4. //
  5. // Created by Ljupco Nastevski on 30.1.22.
  6. //
  7. import Foundation
  8. import UIKit
  9. class LLCache: NSCache <NSString, UIImage> {
  10. static let shared: LLCache = LLCache()
  11. weak var activeTask: URLSessionDataTask?
  12. override init() {
  13. super.init()
  14. self.name = "com.livelike.gif_cache"
  15. }
  16. func retreiveDataFromUrl(url: URL, completion: @escaping (UIImage?) -> Void) {
  17. let path = url.path
  18. if let stored = self.object(forKey: path as NSString) {
  19. completion(stored)
  20. return
  21. }
  22. activeTask = GiphyApiManager.shared.getData(url: url) { [weak self] data in
  23. var preparedImage: UIImage?
  24. if let data = data {
  25. preparedImage = self?.prepareData(data: data)
  26. if preparedImage != nil {
  27. self?.setObject(preparedImage!, forKey: path as NSString)
  28. }
  29. }
  30. completion(preparedImage)
  31. }
  32. }
  33. func cancelTaskFor(url: URL) {
  34. GiphyApiManager.shared.cancelDataTaskForUrl(url: url)
  35. }
  36. /*!
  37. Prepare the gif before saving it.
  38. The loading will be faster.
  39. */
  40. private func prepareData(data: Data) -> UIImage? {
  41. guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
  42. var images = [UIImage]()
  43. let imageCount = CGImageSourceGetCount(source)
  44. for i in 0 ..< imageCount {
  45. if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
  46. let img = self.drawInContext(image: UIImage(cgImage: image))
  47. images.append(img)
  48. }
  49. }
  50. let animatedImage = UIImage.animatedImage(with: images, duration: TimeInterval(images.count * (1/15)))
  51. return animatedImage
  52. }
  53. private func drawInContext(image: UIImage) -> UIImage {
  54. UIGraphicsBeginImageContextWithOptions(image.size, true, 1)
  55. image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
  56. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  57. UIGraphicsEndImageContext()
  58. return newImage!
  59. }
  60. }