-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSessionTaskFactory.swift
More file actions
211 lines (180 loc) · 9.33 KB
/
Copy pathSessionTaskFactory.swift
File metadata and controls
211 lines (180 loc) · 9.33 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// SessionTaskFactory.swift
//
// Copyright © 2018-2021 Vasilis Panagiotopoulos. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// Factory class that creates Session task for each specific case
internal class SessionTaskFactory {
/// Creates a data task request.
/// - Parameters:
/// - Request: A Request instance
/// - completionHandler: A completion handler for success
/// - onFailure: A completion handler for failures
static func makeDataTask(with request: Request,
completionHandler: ((Data, URLResponse?) -> Void)?,
onFailure: FailureCallback?) -> URLSessionDataTask? {
// Hold completionHandler for later use.
request.successCompletionHandler = completionHandler
let urlRequest: URLRequest!
do {
urlRequest = try request.asRequest()
} catch let error {
guard let tnError = error as? TNError else {
return nil
}
request.handleDataTaskCompleted(with: nil,
error: tnError,
onFailureCallback: { onFailure?(tnError, nil) })
return nil
}
/// Create mock response if needed
if request.shouldMockResponse() {
return request.createMockResponse(request: urlRequest,
completionHandler: completionHandler,
onFailure: onFailure)
}
let session = URLSession(configuration: URLSessionConfiguration.default,
delegate: Session<Data>(with: request),
delegateQueue: OperationQueue.current)
let dataTask = session.dataTask(with: urlRequest) { data, urlResponse, error in
request.urlResponse = urlResponse
let dataResult = RequestHelpers.processData(with: request,
data: data,
urlResponse: urlResponse,
serverError: error)
if let tnError = dataResult.tnError {
onFailure?(tnError, data)
} else {
completionHandler?(dataResult.data ?? Data(), urlResponse)
}
}
return dataTask
}
/// Creates an upload task request.
/// - Parameters:
/// - Request: A Request instance
/// - completionHandler: A completion handler for success
/// - onFailure: A completion handler for failures
static func makeUploadTask(with request: Request,
progressUpdate: ProgressCallbackType?,
completionHandler: ((Data, URLResponse?) -> Void)?,
onFailure: FailureCallback?) -> URLSessionUploadTask? {
// Hold completionHandler for later use.
request.successCompletionHandler = completionHandler
request.progressCallback = progressUpdate
guard let params = request.params as? [String: MultipartFormDataPartType] else {
onFailure?(.invalidMultipartParams, nil)
return nil
}
// Set the type of the request
request.requestType = .upload
var urlRequest: URLRequest
let boundary = MultipartFormDataHelpers.generateBoundary()
request.configuration.requestBodyType = .multipartFormData(boundary: boundary)
request.multipartBoundary = boundary
do {
request.multipartFormDataStream = try MultipartFormDataStream(request: request,
params: params,
boundary: boundary,
uploadProgressCallback: progressUpdate)
urlRequest = try request.asRequest()
} catch let error {
guard let tnError = error as? TNError else {
return nil
}
onFailure?(tnError, nil)
return nil
}
let sessionDelegate = Session<Data>(with: request,
progressCallback: progressUpdate,
completedCallback: { (data, urlResponse, error) in
request.urlResponse = urlResponse
let dataResult = RequestHelpers.processData(with: request,
data: data,
urlResponse: urlResponse,
serverError: error)
if let tnError = dataResult.tnError {
request.handleDataTaskCompleted(with: dataResult.data,
error: tnError,
onFailureCallback: { onFailure?(tnError, dataResult.data) })
} else {
completionHandler?(dataResult.data ?? Data(), urlResponse)
}
}, failureCallback: onFailure)
let session = URLSession(configuration: URLSessionConfiguration.default,
delegate: sessionDelegate,
delegateQueue: OperationQueue.current)
let uploadTask = session.uploadTask(withStreamedRequest: urlRequest)
return uploadTask
}
/// Creates a download task request.
/// - Parameters:
/// - Request: A Request instance
/// - completionHandler: A completion handler for success
/// - onFailure: A completion handler for failures
static func makeDownloadTask(with request: Request,
filePath destinationPath: String,
progressUpdate: ProgressCallbackType?,
completionHandler: ((Data?, URLResponse?) -> Void)?,
onFailure: FailureCallback?) -> URLSessionDownloadTask? {
// Hold completionHandler for later use.
request.successCompletionHandler = completionHandler
let urlRequest: URLRequest!
do {
urlRequest = try request.asRequest()
} catch let error {
guard let tnError = error as? TNError else {
return nil
}
request.handleDataTaskCompleted(with: nil,
error: tnError,
onFailureCallback: { onFailure?(tnError, nil) })
return nil
}
// Set the type of the request
request.requestType = .download(destinationPath)
let callback: ((URL?, URLResponse?, Error?) -> Void)? = { url, urlResponse, error in
request.urlResponse = urlResponse
let dataResult = RequestHelpers.processData(with: request,
urlResponse: urlResponse,
serverError: error)
if let tnError = dataResult.tnError {
onFailure?(tnError, nil)
} else {
if let path = url?.path {
do {
try FileManager.default.moveItem(atPath: path, toPath: destinationPath)
completionHandler?(dataResult.data, urlResponse)
} catch let error {
let tnError = TNError.downloadedFileCannotBeSaved(error)
onFailure?(tnError, nil)
return
}
}
}
}
let session = URLSession(configuration: URLSessionConfiguration.default,
delegate: Session<URL>(with: request,
progressCallback: progressUpdate,
completedCallback: callback,
failureCallback: onFailure),
delegateQueue: OperationQueue.current)
let task = session.downloadTask(with: urlRequest)
task.resume()
return task
}
}