-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageCache.swift
98 lines (80 loc) · 2.66 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//
// ImageCache.swift
// Example-Data-Races-In-Image-Loading
//
// Created by Rozeri Dilar on 19.06.2023.
//
import UIKit
public class ImageCache {
private let urlSession: URLSession
private let cachedImages = NSCache<NSURL, UIImage>()
private var loadingResponses = [NSURL: [(ImageItem, UIImage?) -> Swift.Void]]()
private var runningRequests = [NSURL: URLSessionDataTask]()
private let syncQueue = DispatchQueue(label: "Queue to sync mutation")
public final func image(url: NSURL) -> UIImage? {
syncQueue.sync {
return cachedImages.object(forKey: url)
}
}
public init(session: URLSession = URLSession.shared,
totalCostLimit: Int = 100 * 1024 * 1024) {
self.urlSession = session
cachedImages.totalCostLimit = totalCostLimit
}
public final func load(
url: NSURL,
item: ImageItem,
queue: DispatchQueue = .main,
completion: @escaping (ImageItem, UIImage?) -> Swift.Void
) {
if let cachedImage = image(url: url) {
queue.async { [weak self] in
guard self != nil else { return }
completion(item, cachedImage)
}
return
}
syncQueue.sync {
if self.loadingResponses[url] != nil {
self.loadingResponses[url]?.append(completion)
return
} else {
self.loadingResponses[url] = [completion]
}
}
let task = urlSession.dataTask(with: url as URL) { [weak self] data, _, error in
guard let self = self,
let responseData = data,
let image = UIImage(data: responseData),
let blocks = self.loadingResponses[url],
error == nil
else {
queue.async { [weak self] in
guard self != nil else { return }
completion(item, nil)
}
return
}
self.syncQueue.sync {
self.cachedImages.setObject(image, forKey: url, cost: responseData.count)
}
for block in blocks {
queue.async { [weak self] in
guard self != nil else { return }
block(item, image)
}
return
}
}
task.resume()
syncQueue.sync {
self.runningRequests[url] = task
}
}
public func cancelLoad(_ url: NSURL) {
syncQueue.sync {
self.runningRequests[url]?.cancel()
self.runningRequests.removeValue(forKey: url)
}
}
}