-
Notifications
You must be signed in to change notification settings - Fork 5
/
ImageCache.swift
41 lines (33 loc) · 1.17 KB
/
ImageCache.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//
// ImageCache.swift
// Movie ticket booking app
//
// Created by Akash soni on 08/11/22.
//
import UIKit
struct Constants {
static var imageCache = NSCache<AnyObject, AnyObject>()
}
extension UIImageView {
func downloadImage(urlString: String) {
guard let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) else { return }
image = nil
if let imageFromCache = Constants.imageCache.object(forKey: urlString as AnyObject) as? UIImage {
DispatchQueue.main.async {
self.image = imageFromCache
}
} else {
URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let self = self, let imageData = data else { return }
Constants.imageCache.setObject(data as AnyObject, forKey: urlString as AnyObject)
DispatchQueue.main.async {
if error != nil {
self.image = nil
} else {
self.image = UIImage(data: imageData)
}
}
}.resume()
}
}
}