This repository has been archived by the owner on Dec 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 98
/
URLSessionCoordinator.swift
194 lines (150 loc) · 6.81 KB
/
URLSessionCoordinator.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//
// URLSessionCoordinator.swift
//
//
// Created by Dmytro Anokhin on 07/07/2020.
//
import Foundation
import Combine
import Log
/// `URLSessionCoordinator` manages `URLSession` instance and forwards callbacks to responding `DownloadController` instances.
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
final class URLSessionCoordinator {
init(urlSessionConfiguration: URLSessionConfiguration) {
let delegate = URLSessionDelegate()
urlSession = URLSession(configuration: urlSessionConfiguration, delegate: delegate, delegateQueue: nil)
delegate
.onTaskDidCompleteWithError { [weak self] urlSessionTask, error in
guard let self = self else {
return
}
self.async {
let downloadTaskID = urlSessionTask.taskDescription!
guard let downloadTask = self.registry[downloadTaskID] else {
// This can happen when the task was cancelled
return
}
self.registry[downloadTaskID] = nil
if let error = error {
downloadTask.complete(withError: error)
}
else {
downloadTask.complete()
}
}
}
.onDataTaskDidReceiveData { [weak self] urlSessionTask, data in
guard let self = self else {
return
}
self.async {
let downloadTaskID = urlSessionTask.taskDescription!
guard let downloadTask = self.registry[downloadTaskID] else {
// This can happen when the task was cancelled
return
}
downloadTask.receive(data: data)
}
}
.onDataTaskDidReceiveResponse { [weak self] task, response, completion in
guard let self = self else {
completion(.cancel)
return
}
self.async {
let downloadTaskID = task.taskDescription!
guard let downloadTask = self.registry[downloadTaskID] else {
// This can happen when the task was cancelled
completion(.cancel)
return
}
downloadTask.receive(response: response)
completion(.allow)
}
}
.onDownloadTaskDidFinishDownloadingTo { [weak self] task, location in
guard let self = self else {
return
}
self.sync {
let downloadTaskID = task.taskDescription!
guard let downloadTask = self.registry[downloadTaskID] else {
// This can happen when the task was cancelled
return
}
guard case Download.Destination.onDisk(let path) = downloadTask.download.destination else {
assertionFailure("Expected file path destination for download task")
return
}
let destination = URL(fileURLWithPath: path)
try? FileManager.default.moveItem(at: location, to: destination)
}
}
.onDownloadTaskDidWriteData { [weak self] task, _, totalBytesWritten, totalBytesExpectedToWrite in
guard let self = self else {
return
}
self.async {
let downloadTaskID = task.taskDescription!
guard let downloadTask = self.registry[downloadTaskID] else {
// This can happen when the task was cancelled
return
}
downloadTask.downloadProgress(received: totalBytesWritten, expected: totalBytesExpectedToWrite)
}
}
}
func startDownload(_ download: Download,
receiveResponse: @escaping DownloadReceiveResponse,
receiveData: @escaping DownloadReceiveData,
reportProgress: @escaping DownloadReportProgress,
completion: @escaping DownloadCompletion) {
async {
log_debug(self, #function, "download.id = \(download.id), download.url: \(download.url)", detail: log_normal)
let downloadTaskID = download.id.uuidString
guard self.registry[downloadTaskID] == nil else {
assertionFailure("Can not start \(download) twice")
return
}
let observer = DownloadTask.Observer(download: download, receiveResponse: receiveResponse, receiveData: receiveData, reportProgress: reportProgress, completion: completion)
let downloadTask = self.makeDownloadTask(for: download, withObserver: observer)
self.registry[downloadTaskID] = downloadTask
downloadTask.urlSessionTask.resume()
}
}
func cancelDownload(_ download: Download) {
async {
log_debug(self, #function, "download.id = \(download.id), download.url: \(download.url)", detail: log_normal)
let downloadTaskID = download.id.uuidString
guard let downloadTask = self.registry[downloadTaskID] else {
return
}
downloadTask.urlSessionTask.cancel()
self.registry[downloadTaskID] = nil
}
}
// MARK: - Private
private let urlSession: URLSession
private func makeDownloadTask(for download: Download, withObserver observer: DownloadTask.Observer) -> DownloadTask {
let urlSessionTask: URLSessionTask
var request = URLRequest(url: download.url)
request.allHTTPHeaderFields = download.urlRequestConfiguration.allHTTPHeaderFields
switch download.destination {
case .inMemory:
urlSessionTask = urlSession.dataTask(with: request)
case .onDisk:
urlSessionTask = urlSession.downloadTask(with: request)
}
urlSessionTask.taskDescription = download.id.uuidString
return DownloadTask(download: download, urlSessionTask: urlSessionTask, observer: observer)
}
private typealias DownloadTaskID = String
private var registry: [DownloadTaskID: DownloadTask] = [:]
private let serialQueue = DispatchQueue(label: "URLSessionCoordinator.serialQueue")
private func async(_ closure: @escaping () -> Void) {
serialQueue.async(execute: closure)
}
private func sync(_ closure: () -> Void) {
serialQueue.sync(execute: closure)
}
}