TaskDelegate.swift 13 KB

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