TaskDelegate.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. //
  2. // Error.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. let progress: Progress
  33. var data: Data? { return nil }
  34. var error: NSError?
  35. var initialResponseTime: CFAbsoluteTime?
  36. var credential: URLCredential?
  37. // MARK: Lifecycle
  38. init(task: URLSessionTask) {
  39. self.task = task
  40. self.progress = Progress(totalUnitCount: 0)
  41. self.queue = {
  42. let operationQueue = OperationQueue()
  43. operationQueue.maxConcurrentOperationCount = 1
  44. operationQueue.isSuspended = true
  45. operationQueue.qualityOfService = .utility
  46. return operationQueue
  47. }()
  48. }
  49. // MARK: NSURLSessionTaskDelegate
  50. var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
  51. var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
  52. var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
  53. var taskDidCompleteWithError: ((URLSession, URLSessionTask, NSError?) -> Void)?
  54. @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
  55. func urlSession(
  56. _ session: URLSession,
  57. task: URLSessionTask,
  58. willPerformHTTPRedirection response: HTTPURLResponse,
  59. newRequest request: URLRequest,
  60. completionHandler: @escaping (URLRequest?) -> Void)
  61. {
  62. var redirectRequest: URLRequest? = request
  63. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  64. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  65. }
  66. completionHandler(redirectRequest)
  67. }
  68. @objc(URLSession:task:didReceiveChallenge:completionHandler:)
  69. func urlSession(
  70. _ session: URLSession,
  71. task: URLSessionTask,
  72. didReceive challenge: URLAuthenticationChallenge,
  73. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  74. {
  75. var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
  76. var credential: URLCredential?
  77. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  78. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  79. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  80. let host = challenge.protectionSpace.host
  81. if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
  82. let serverTrust = challenge.protectionSpace.serverTrust
  83. {
  84. if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
  85. disposition = .useCredential
  86. credential = URLCredential(trust: serverTrust)
  87. } else {
  88. disposition = .cancelAuthenticationChallenge
  89. }
  90. }
  91. } else {
  92. if challenge.previousFailureCount > 0 {
  93. disposition = .rejectProtectionSpace
  94. } else {
  95. credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
  96. if credential != nil {
  97. disposition = .useCredential
  98. }
  99. }
  100. }
  101. completionHandler(disposition, credential)
  102. }
  103. @objc(URLSession:task:needNewBodyStream:)
  104. func urlSession(
  105. _ session: URLSession,
  106. task: URLSessionTask,
  107. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
  108. {
  109. var bodyStream: InputStream?
  110. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  111. bodyStream = taskNeedNewBodyStream(session, task)
  112. }
  113. completionHandler(bodyStream)
  114. }
  115. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
  116. if let taskDidCompleteWithError = taskDidCompleteWithError {
  117. taskDidCompleteWithError(session, task, error)
  118. } else {
  119. if let error = error {
  120. self.error = error
  121. if
  122. let downloadDelegate = self as? DownloadTaskDelegate,
  123. let resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
  124. {
  125. downloadDelegate.resumeData = resumeData
  126. }
  127. }
  128. queue.isSuspended = false
  129. }
  130. }
  131. }
  132. // MARK: -
  133. class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
  134. // MARK: Properties
  135. var dataTask: URLSessionDataTask? { return task as? URLSessionDataTask }
  136. override var data: Data? {
  137. if dataStream != nil {
  138. return nil
  139. } else {
  140. return mutableData as Data
  141. }
  142. }
  143. var dataProgress: ((_ bytesReceived: Int64, _ totalBytesReceived: Int64, _ totalBytesExpectedToReceive: Int64) -> Void)?
  144. var dataStream: ((_ data: Data) -> Void)?
  145. private var totalBytesReceived: Int64 = 0
  146. private var mutableData: Data
  147. private var expectedContentLength: Int64?
  148. // MARK: Lifecycle
  149. override init(task: URLSessionTask) {
  150. mutableData = Data()
  151. super.init(task: task)
  152. }
  153. // MARK: NSURLSessionDataDelegate
  154. var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
  155. var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
  156. var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
  157. var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
  158. func urlSession(
  159. _ session: URLSession,
  160. dataTask: URLSessionDataTask,
  161. didReceive response: URLResponse,
  162. completionHandler: ((URLSession.ResponseDisposition) -> Void))
  163. {
  164. var disposition: URLSession.ResponseDisposition = .allow
  165. expectedContentLength = response.expectedContentLength
  166. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  167. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  168. }
  169. completionHandler(disposition)
  170. }
  171. func urlSession(
  172. _ session: URLSession,
  173. dataTask: URLSessionDataTask,
  174. didBecome downloadTask: URLSessionDownloadTask)
  175. {
  176. dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  177. }
  178. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  179. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  180. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  181. dataTaskDidReceiveData(session, dataTask, data)
  182. } else {
  183. if let dataStream = dataStream {
  184. dataStream(data)
  185. } else {
  186. mutableData.append(data)
  187. }
  188. let bytesReceived = Int64(data.count)
  189. totalBytesReceived += bytesReceived
  190. let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  191. progress.totalUnitCount = totalBytesExpected
  192. progress.completedUnitCount = totalBytesReceived
  193. dataProgress?(
  194. bytesReceived,
  195. totalBytesReceived,
  196. totalBytesExpected
  197. )
  198. }
  199. }
  200. func urlSession(
  201. _ session: URLSession,
  202. dataTask: URLSessionDataTask,
  203. willCacheResponse proposedResponse: CachedURLResponse,
  204. completionHandler: ((CachedURLResponse?) -> Void))
  205. {
  206. var cachedResponse: CachedURLResponse? = proposedResponse
  207. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  208. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  209. }
  210. completionHandler(cachedResponse)
  211. }
  212. }
  213. // MARK: -
  214. class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
  215. // MARK: Properties
  216. var downloadTask: URLSessionDownloadTask? { return task as? URLSessionDownloadTask }
  217. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  218. var resumeData: Data?
  219. override var data: Data? { return resumeData }
  220. // MARK: NSURLSessionDownloadDelegate
  221. var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
  222. var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  223. var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
  224. func urlSession(
  225. _ session: URLSession,
  226. downloadTask: URLSessionDownloadTask,
  227. didFinishDownloadingTo location: URL)
  228. {
  229. if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
  230. do {
  231. let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
  232. try FileManager.default.moveItem(at: location, to: destination)
  233. } catch {
  234. self.error = error as NSError
  235. }
  236. }
  237. }
  238. func urlSession(
  239. _ session: URLSession,
  240. downloadTask: URLSessionDownloadTask,
  241. didWriteData bytesWritten: Int64,
  242. totalBytesWritten: Int64,
  243. totalBytesExpectedToWrite: Int64)
  244. {
  245. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  246. if let downloadTaskDidWriteData = downloadTaskDidWriteData {
  247. downloadTaskDidWriteData(
  248. session,
  249. downloadTask,
  250. bytesWritten,
  251. totalBytesWritten,
  252. totalBytesExpectedToWrite
  253. )
  254. } else {
  255. progress.totalUnitCount = totalBytesExpectedToWrite
  256. progress.completedUnitCount = totalBytesWritten
  257. downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  258. }
  259. }
  260. func urlSession(
  261. _ session: URLSession,
  262. downloadTask: URLSessionDownloadTask,
  263. didResumeAtOffset fileOffset: Int64,
  264. expectedTotalBytes: Int64)
  265. {
  266. if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
  267. downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
  268. } else {
  269. progress.totalUnitCount = expectedTotalBytes
  270. progress.completedUnitCount = fileOffset
  271. }
  272. }
  273. }
  274. // MARK: -
  275. class UploadTaskDelegate: DataTaskDelegate {
  276. // MARK: Properties
  277. var uploadTask: URLSessionUploadTask? { return task as? URLSessionUploadTask }
  278. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  279. // MARK: NSURLSessionTaskDelegate
  280. var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
  281. func URLSession(
  282. _ session: URLSession,
  283. task: URLSessionTask,
  284. didSendBodyData bytesSent: Int64,
  285. totalBytesSent: Int64,
  286. totalBytesExpectedToSend: Int64)
  287. {
  288. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  289. if let taskDidSendBodyData = taskDidSendBodyData {
  290. taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
  291. } else {
  292. progress.totalUnitCount = totalBytesExpectedToSend
  293. progress.completedUnitCount = totalBytesSent
  294. uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  295. }
  296. }
  297. }