TaskDelegate.swift 13 KB

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