1 |
efrain |
1 |
//
|
|
|
2 |
// ImageLoader.swift
|
|
|
3 |
// twogetskills
|
|
|
4 |
//
|
|
|
5 |
// Created by Efrain Yanez Recanatini on 3/9/22.
|
|
|
6 |
//
|
|
|
7 |
|
|
|
8 |
import Combine
|
|
|
9 |
import UIKit
|
|
|
10 |
|
|
|
11 |
|
|
|
12 |
class ImageLoader: ObservableObject {
|
|
|
13 |
@Published var image: UIImage?
|
|
|
14 |
|
|
|
15 |
private(set) var isLoading = false
|
|
|
16 |
|
|
|
17 |
private let url: URL
|
|
|
18 |
private var cache: ImageCache?
|
|
|
19 |
private var cancellable: AnyCancellable?
|
|
|
20 |
|
|
|
21 |
private static let imageProcessingQueue = DispatchQueue(label: "image-processing")
|
|
|
22 |
|
|
|
23 |
init(url: URL, cache: ImageCache? = nil) {
|
|
|
24 |
self.url = url
|
|
|
25 |
self.cache = cache
|
|
|
26 |
}
|
|
|
27 |
|
|
|
28 |
deinit {
|
|
|
29 |
cancel()
|
|
|
30 |
}
|
|
|
31 |
|
|
|
32 |
func load() {
|
|
|
33 |
guard !isLoading else { return }
|
|
|
34 |
|
|
|
35 |
if let image = cache?[url] {
|
|
|
36 |
self.image = image
|
|
|
37 |
return
|
|
|
38 |
}
|
|
|
39 |
|
|
|
40 |
let preference = Preference.sharedInstance
|
|
|
41 |
let headerSecurity = HeaderSecurity()
|
|
|
42 |
|
|
|
43 |
|
|
|
44 |
|
|
|
45 |
var request = URLRequest(url: url)
|
|
|
46 |
request.httpMethod = "GET"
|
|
|
47 |
request.addValue(preference.deviceUuid, forHTTPHeaderField: Constants.HTTP_HEADER_SECURITY_TOKEN)
|
|
|
48 |
request.addValue(headerSecurity.secret, forHTTPHeaderField: Constants.HTTP_HEADER_SECURITY_SECRET)
|
|
|
49 |
request.addValue(String(headerSecurity.created), forHTTPHeaderField: Constants.HTTP_HEADER_SECURITY_CREATED)
|
|
|
50 |
request.addValue(String(headerSecurity.rand), forHTTPHeaderField: "Content-Type")
|
|
|
51 |
|
|
|
52 |
|
|
|
53 |
cancellable = URLSession.shared.dataTaskPublisher(for: request)
|
|
|
54 |
.map { UIImage(data: $0.data) }
|
|
|
55 |
.replaceError(with: nil)
|
|
|
56 |
.handleEvents(receiveSubscription: { [weak self] _ in self?.onStart() },
|
|
|
57 |
receiveOutput: { [weak self] in self?.cache($0) },
|
|
|
58 |
receiveCompletion: { [weak self] _ in self?.onFinish() },
|
|
|
59 |
receiveCancel: { [weak self] in self?.onFinish() })
|
|
|
60 |
.subscribe(on: Self.imageProcessingQueue)
|
|
|
61 |
.receive(on: DispatchQueue.main)
|
|
|
62 |
.sink { [weak self] in self?.image = $0 }
|
|
|
63 |
}
|
|
|
64 |
|
|
|
65 |
func cancel() {
|
|
|
66 |
cancellable?.cancel()
|
|
|
67 |
}
|
|
|
68 |
|
|
|
69 |
private func onStart() {
|
|
|
70 |
isLoading = true
|
|
|
71 |
}
|
|
|
72 |
|
|
|
73 |
private func onFinish() {
|
|
|
74 |
isLoading = false
|
|
|
75 |
}
|
|
|
76 |
|
|
|
77 |
private func cache(_ image: UIImage?) {
|
|
|
78 |
image.map { cache?[url] = $0 }
|
|
|
79 |
}
|
|
|
80 |
|
|
|
81 |
}
|