TaskDelegate.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //
  2. // TaskDelegate.swift
  3. //
  4. // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
  26. /// executing all operations attached to the serial operation queue upon task completion.
  27. open class TaskDelegate: NSObject {
  28. // MARK: Properties
  29. /// The serial operation queue used to execute all operations after the task completes.
  30. open let queue: OperationQueue
  31. var task: URLSessionTask? {
  32. didSet { reset() }
  33. }
  34. var data: Data? { return nil }
  35. var error: Error?
  36. var initialResponseTime: CFAbsoluteTime?
  37. var credential: URLCredential?
  38. var metrics: AnyObject? // URLSessionTaskMetrics
  39. // MARK: Lifecycle
  40. init(task: URLSessionTask?) {
  41. self.task = task
  42. self.queue = {
  43. let operationQueue = OperationQueue()
  44. operationQueue.maxConcurrentOperationCount = 1
  45. operationQueue.isSuspended = true
  46. operationQueue.qualityOfService = .utility
  47. return operationQueue
  48. }()
  49. }
  50. func reset() {
  51. error = nil
  52. initialResponseTime = nil
  53. }
  54. // MARK: URLSessionTaskDelegate
  55. var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
  56. var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
  57. var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
  58. var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
  59. @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
  60. func urlSession(
  61. _ session: URLSession,
  62. task: URLSessionTask,
  63. willPerformHTTPRedirection response: HTTPURLResponse,
  64. newRequest request: URLRequest,
  65. completionHandler: @escaping (URLRequest?) -> Void)
  66. {
  67. var redirectRequest: URLRequest? = request
  68. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  69. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  70. }
  71. completionHandler(redirectRequest)
  72. }
  73. @objc(URLSession:task:didReceiveChallenge:completionHandler:)
  74. func urlSession(
  75. _ session: URLSession,
  76. task: URLSessionTask,
  77. didReceive challenge: URLAuthenticationChallenge,
  78. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  79. {
  80. var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
  81. var credential: URLCredential?
  82. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  83. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  84. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  85. let host = challenge.protectionSpace.host
  86. if
  87. let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
  88. let serverTrust = challenge.protectionSpace.serverTrust
  89. {
  90. if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
  91. disposition = .useCredential
  92. credential = URLCredential(trust: serverTrust)
  93. } else {
  94. disposition = .cancelAuthenticationChallenge
  95. }
  96. }
  97. } else {
  98. if challenge.previousFailureCount > 0 {
  99. disposition = .rejectProtectionSpace
  100. } else {
  101. credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
  102. if credential != nil {
  103. disposition = .useCredential
  104. }
  105. }
  106. }
  107. completionHandler(disposition, credential)
  108. }
  109. @objc(URLSession:task:needNewBodyStream:)
  110. func urlSession(
  111. _ session: URLSession,
  112. task: URLSessionTask,
  113. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
  114. {
  115. var bodyStream: InputStream?
  116. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  117. bodyStream = taskNeedNewBodyStream(session, task)
  118. }
  119. completionHandler(bodyStream)
  120. }
  121. @objc(URLSession:task:didCompleteWithError:)
  122. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  123. if let taskDidCompleteWithError = taskDidCompleteWithError {
  124. taskDidCompleteWithError(session, task, error)
  125. } else {
  126. if let error = error {
  127. if self.error == nil { self.error = error }
  128. if
  129. let downloadDelegate = self as? DownloadTaskDelegate,
  130. let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
  131. {
  132. downloadDelegate.resumeData = resumeData
  133. }
  134. }
  135. queue.isSuspended = false
  136. }
  137. }
  138. }
  139. // MARK: -
  140. class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
  141. // MARK: Properties
  142. var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
  143. override var data: Data? {
  144. if dataStream != nil {
  145. return nil
  146. } else {
  147. return mutableData
  148. }
  149. }
  150. var progress: Progress
  151. var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
  152. var dataStream: ((_ data: Data) -> Void)?
  153. private var totalBytesReceived: Int64 = 0
  154. private var mutableData: Data
  155. private var expectedContentLength: Int64?
  156. // MARK: Lifecycle
  157. override init(task: URLSessionTask?) {
  158. mutableData = Data()
  159. progress = Progress(totalUnitCount: 0)
  160. super.init(task: task)
  161. }
  162. override func reset() {
  163. super.reset()
  164. progress = Progress(totalUnitCount: 0)
  165. totalBytesReceived = 0
  166. mutableData = Data()
  167. expectedContentLength = nil
  168. }
  169. // MARK: URLSessionDataDelegate
  170. var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
  171. var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
  172. var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
  173. var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
  174. func urlSession(
  175. _ session: URLSession,
  176. dataTask: URLSessionDataTask,
  177. didReceive response: URLResponse,
  178. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  179. {
  180. var disposition: URLSession.ResponseDisposition = .allow
  181. expectedContentLength = response.expectedContentLength
  182. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  183. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  184. }
  185. completionHandler(disposition)
  186. }
  187. func urlSession(
  188. _ session: URLSession,
  189. dataTask: URLSessionDataTask,
  190. didBecome downloadTask: URLSessionDownloadTask)
  191. {
  192. dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  193. }
  194. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  195. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  196. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  197. dataTaskDidReceiveData(session, dataTask, data)
  198. } else {
  199. if let dataStream = dataStream {
  200. dataStream(data)
  201. } else {
  202. mutableData.append(data)
  203. }
  204. let bytesReceived = Int64(data.count)
  205. totalBytesReceived += bytesReceived
  206. let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  207. progress.totalUnitCount = totalBytesExpected
  208. progress.completedUnitCount = totalBytesReceived
  209. if let progressHandler = progressHandler {
  210. progressHandler.queue.async { progressHandler.closure(self.progress) }
  211. }
  212. }
  213. }
  214. func urlSession(
  215. _ session: URLSession,
  216. dataTask: URLSessionDataTask,
  217. willCacheResponse proposedResponse: CachedURLResponse,
  218. completionHandler: @escaping (CachedURLResponse?) -> Void)
  219. {
  220. var cachedResponse: CachedURLResponse? = proposedResponse
  221. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  222. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  223. }
  224. completionHandler(cachedResponse)
  225. }
  226. }
  227. // MARK: -
  228. class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
  229. // MARK: Properties
  230. var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
  231. var progress: Progress
  232. var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
  233. var resumeData: Data?
  234. override var data: Data? { return resumeData }
  235. var destination: DownloadRequest.DownloadFileDestination?
  236. var temporaryURL: URL?
  237. var destinationURL: URL?
  238. var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
  239. // MARK: Lifecycle
  240. override init(task: URLSessionTask?) {
  241. progress = Progress(totalUnitCount: 0)
  242. super.init(task: task)
  243. }
  244. override func reset() {
  245. super.reset()
  246. progress = Progress(totalUnitCount: 0)
  247. resumeData = nil
  248. }
  249. // MARK: URLSessionDownloadDelegate
  250. var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
  251. var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  252. var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
  253. func urlSession(
  254. _ session: URLSession,
  255. downloadTask: URLSessionDownloadTask,
  256. didFinishDownloadingTo location: URL)
  257. {
  258. temporaryURL = location
  259. if let destination = destination {
  260. let result = destination(location, downloadTask.response as! HTTPURLResponse)
  261. let destination = result.destinationURL
  262. let options = result.options
  263. do {
  264. destinationURL = destination
  265. if options.contains(.removePreviousFile) {
  266. if FileManager.default.fileExists(atPath: destination.path) {
  267. try FileManager.default.removeItem(at: destination)
  268. }
  269. }
  270. if options.contains(.createIntermediateDirectories) {
  271. let directory = destination.deletingLastPathComponent()
  272. try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
  273. }
  274. try FileManager.default.moveItem(at: location, to: destination)
  275. } catch {
  276. self.error = error
  277. }
  278. }
  279. }
  280. func urlSession(
  281. _ session: URLSession,
  282. downloadTask: URLSessionDownloadTask,
  283. didWriteData bytesWritten: Int64,
  284. totalBytesWritten: Int64,
  285. totalBytesExpectedToWrite: Int64)
  286. {
  287. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  288. if let downloadTaskDidWriteData = downloadTaskDidWriteData {
  289. downloadTaskDidWriteData(
  290. session,
  291. downloadTask,
  292. bytesWritten,
  293. totalBytesWritten,
  294. totalBytesExpectedToWrite
  295. )
  296. } else {
  297. progress.totalUnitCount = totalBytesExpectedToWrite
  298. progress.completedUnitCount = totalBytesWritten
  299. if let progressHandler = progressHandler {
  300. progressHandler.queue.async { progressHandler.closure(self.progress) }
  301. }
  302. }
  303. }
  304. func urlSession(
  305. _ session: URLSession,
  306. downloadTask: URLSessionDownloadTask,
  307. didResumeAtOffset fileOffset: Int64,
  308. expectedTotalBytes: Int64)
  309. {
  310. if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
  311. downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
  312. } else {
  313. progress.totalUnitCount = expectedTotalBytes
  314. progress.completedUnitCount = fileOffset
  315. }
  316. }
  317. }
  318. // MARK: -
  319. class UploadTaskDelegate: DataTaskDelegate {
  320. // MARK: Properties
  321. var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
  322. var uploadProgress: Progress
  323. var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
  324. // MARK: Lifecycle
  325. override init(task: URLSessionTask?) {
  326. uploadProgress = Progress(totalUnitCount: 0)
  327. super.init(task: task)
  328. }
  329. override func reset() {
  330. super.reset()
  331. uploadProgress = Progress(totalUnitCount: 0)
  332. }
  333. // MARK: URLSessionTaskDelegate
  334. var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
  335. func URLSession(
  336. _ session: URLSession,
  337. task: URLSessionTask,
  338. didSendBodyData bytesSent: Int64,
  339. totalBytesSent: Int64,
  340. totalBytesExpectedToSend: Int64)
  341. {
  342. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  343. if let taskDidSendBodyData = taskDidSendBodyData {
  344. taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
  345. } else {
  346. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  347. uploadProgress.completedUnitCount = totalBytesSent
  348. if let uploadProgressHandler = uploadProgressHandler {
  349. uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
  350. }
  351. }
  352. }
  353. }