EventMonitor.swift 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. //
  2. // EventMonitor.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various
  26. /// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses.
  27. public protocol EventMonitor {
  28. /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default.
  29. var queue: DispatchQueue { get }
  30. // MARK: - URLSession Events
  31. // MARK: URLSessionDelegate Events
  32. /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method.
  33. func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
  34. // MARK: URLSessionTaskDelegate Events
  35. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method.
  36. func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge)
  37. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method.
  38. func urlSession(_ session: URLSession,
  39. task: URLSessionTask,
  40. didSendBodyData bytesSent: Int64,
  41. totalBytesSent: Int64,
  42. totalBytesExpectedToSend: Int64)
  43. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method.
  44. func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask)
  45. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method.
  46. func urlSession(_ session: URLSession,
  47. task: URLSessionTask,
  48. willPerformHTTPRedirection response: HTTPURLResponse,
  49. newRequest request: URLRequest)
  50. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method.
  51. func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
  52. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method.
  53. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
  54. /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method.
  55. func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
  56. // MARK: URLSessionDataDelegate Events
  57. /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:completionHandler:)` method.
  58. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse)
  59. /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method.
  60. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
  61. /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method.
  62. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse)
  63. // MARK: URLSessionDownloadDelegate Events
  64. /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method.
  65. func urlSession(_ session: URLSession,
  66. downloadTask: URLSessionDownloadTask,
  67. didResumeAtOffset fileOffset: Int64,
  68. expectedTotalBytes: Int64)
  69. /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method.
  70. func urlSession(_ session: URLSession,
  71. downloadTask: URLSessionDownloadTask,
  72. didWriteData bytesWritten: Int64,
  73. totalBytesWritten: Int64,
  74. totalBytesExpectedToWrite: Int64)
  75. /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method.
  76. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
  77. // MARK: - Request Events
  78. /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the
  79. /// `URLRequest` will be adapted before being issued.
  80. func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest)
  81. /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails.
  82. func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError)
  83. /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`.
  84. func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest)
  85. /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`.
  86. func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError)
  87. /// Event called when a final `URLRequest` is created for a `Request`.
  88. func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest)
  89. /// Event called when a `URLSessionTask` subclass instance is created for a `Request`.
  90. func request(_ request: Request, didCreateTask task: URLSessionTask)
  91. /// Event called when a `Request` receives a `URLSessionTaskMetrics` value.
  92. func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics)
  93. /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails.
  94. func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError)
  95. /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event
  96. /// multiple times if it is retried.
  97. func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
  98. /// Event called when a `Request` is about to be retried.
  99. func requestIsRetrying(_ request: Request)
  100. /// Event called when a `Request` finishes and response serializers are being called.
  101. func requestDidFinish(_ request: Request)
  102. /// Event called when a `Request` receives a `resume` call.
  103. func requestDidResume(_ request: Request)
  104. /// Event called when a `Request`'s associated `URLSessionTask` is resumed.
  105. func request(_ request: Request, didResumeTask task: URLSessionTask)
  106. /// Event called when a `Request` receives a `suspend` call.
  107. func requestDidSuspend(_ request: Request)
  108. /// Event called when a `Request`'s associated `URLSessionTask` is suspended.
  109. func request(_ request: Request, didSuspendTask task: URLSessionTask)
  110. /// Event called when a `Request` receives a `cancel` call.
  111. func requestDidCancel(_ request: Request)
  112. /// Event called when a `Request`'s associated `URLSessionTask` is cancelled.
  113. func request(_ request: Request, didCancelTask task: URLSessionTask)
  114. // MARK: DataRequest Events
  115. /// Event called when a `DataRequest` calls a `Validation`.
  116. func request(_ request: DataRequest,
  117. didValidateRequest urlRequest: URLRequest?,
  118. response: HTTPURLResponse,
  119. data: Data?,
  120. withResult result: Request.ValidationResult)
  121. /// Event called when a `DataRequest` creates a `DataResponse<Data?>` value without calling a `ResponseSerializer`.
  122. func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>)
  123. /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse<Value, AFError>`.
  124. func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>)
  125. // MARK: DataStreamRequest Events
  126. /// Event called when a `DataStreamRequest` calls a `Validation` closure.
  127. ///
  128. /// - Parameters:
  129. /// - request: `DataStreamRequest` which is calling the `Validation`.
  130. /// - urlRequest: `URLRequest` of the request being validated.
  131. /// - response: `HTTPURLResponse` of the request being validated.
  132. /// - result: Produced `ValidationResult`.
  133. func request(_ request: DataStreamRequest,
  134. didValidateRequest urlRequest: URLRequest?,
  135. response: HTTPURLResponse,
  136. withResult result: Request.ValidationResult)
  137. /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`.
  138. ///
  139. /// - Parameters:
  140. /// - request: `DataStreamRequest` for which the value was serialized.
  141. /// - result: `Result` of the serialization attempt.
  142. func request<Value>(_ request: DataStreamRequest, didParseStream result: Result<Value, AFError>)
  143. // MARK: UploadRequest Events
  144. /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents.
  145. func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable)
  146. /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error.
  147. func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError)
  148. /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if
  149. /// the `InputStream` does not wrap a `Data` value or file `URL`.
  150. func request(_ request: UploadRequest, didProvideInputStream stream: InputStream)
  151. // MARK: DownloadRequest Events
  152. /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved.
  153. func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>)
  154. /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the
  155. /// downloaded file will be moved to.
  156. func request(_ request: DownloadRequest, didCreateDestinationURL url: URL)
  157. /// Event called when a `DownloadRequest` calls a `Validation`.
  158. func request(_ request: DownloadRequest,
  159. didValidateRequest urlRequest: URLRequest?,
  160. response: HTTPURLResponse,
  161. fileURL: URL?,
  162. withResult result: Request.ValidationResult)
  163. /// Event called when a `DownloadRequest` creates a `DownloadResponse<URL?, AFError>` without calling a `ResponseSerializer`.
  164. func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>)
  165. /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse<Value, AFError>`
  166. func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value, AFError>)
  167. }
  168. extension EventMonitor {
  169. /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default.
  170. public var queue: DispatchQueue { .main }
  171. // MARK: Default Implementations
  172. public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {}
  173. public func urlSession(_ session: URLSession,
  174. task: URLSessionTask,
  175. didReceive challenge: URLAuthenticationChallenge) {}
  176. public func urlSession(_ session: URLSession,
  177. task: URLSessionTask,
  178. didSendBodyData bytesSent: Int64,
  179. totalBytesSent: Int64,
  180. totalBytesExpectedToSend: Int64) {}
  181. public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {}
  182. public func urlSession(_ session: URLSession,
  183. task: URLSessionTask,
  184. willPerformHTTPRedirection response: HTTPURLResponse,
  185. newRequest request: URLRequest) {}
  186. public func urlSession(_ session: URLSession,
  187. task: URLSessionTask,
  188. didFinishCollecting metrics: URLSessionTaskMetrics) {}
  189. public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {}
  190. public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {}
  191. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {}
  192. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}
  193. public func urlSession(_ session: URLSession,
  194. dataTask: URLSessionDataTask,
  195. willCacheResponse proposedResponse: CachedURLResponse) {}
  196. public func urlSession(_ session: URLSession,
  197. downloadTask: URLSessionDownloadTask,
  198. didResumeAtOffset fileOffset: Int64,
  199. expectedTotalBytes: Int64) {}
  200. public func urlSession(_ session: URLSession,
  201. downloadTask: URLSessionDownloadTask,
  202. didWriteData bytesWritten: Int64,
  203. totalBytesWritten: Int64,
  204. totalBytesExpectedToWrite: Int64) {}
  205. public func urlSession(_ session: URLSession,
  206. downloadTask: URLSessionDownloadTask,
  207. didFinishDownloadingTo location: URL) {}
  208. public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {}
  209. public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {}
  210. public func request(_ request: Request,
  211. didAdaptInitialRequest initialRequest: URLRequest,
  212. to adaptedRequest: URLRequest) {}
  213. public func request(_ request: Request,
  214. didFailToAdaptURLRequest initialRequest: URLRequest,
  215. withError error: AFError) {}
  216. public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {}
  217. public func request(_ request: Request, didCreateTask task: URLSessionTask) {}
  218. public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {}
  219. public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {}
  220. public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {}
  221. public func requestIsRetrying(_ request: Request) {}
  222. public func requestDidFinish(_ request: Request) {}
  223. public func requestDidResume(_ request: Request) {}
  224. public func request(_ request: Request, didResumeTask task: URLSessionTask) {}
  225. public func requestDidSuspend(_ request: Request) {}
  226. public func request(_ request: Request, didSuspendTask task: URLSessionTask) {}
  227. public func requestDidCancel(_ request: Request) {}
  228. public func request(_ request: Request, didCancelTask task: URLSessionTask) {}
  229. public func request(_ request: DataRequest,
  230. didValidateRequest urlRequest: URLRequest?,
  231. response: HTTPURLResponse,
  232. data: Data?,
  233. withResult result: Request.ValidationResult) {}
  234. public func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>) {}
  235. public func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {}
  236. public func request(_ request: DataStreamRequest,
  237. didValidateRequest urlRequest: URLRequest?,
  238. response: HTTPURLResponse,
  239. withResult result: Request.ValidationResult) {}
  240. public func request<Value>(_ request: DataStreamRequest, didParseStream result: Result<Value, AFError>) {}
  241. public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {}
  242. public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {}
  243. public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {}
  244. public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>) {}
  245. public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {}
  246. public func request(_ request: DownloadRequest,
  247. didValidateRequest urlRequest: URLRequest?,
  248. response: HTTPURLResponse,
  249. fileURL: URL?,
  250. withResult result: Request.ValidationResult) {}
  251. public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>) {}
  252. public func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value, AFError>) {}
  253. }
  254. /// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues.
  255. public final class CompositeEventMonitor: EventMonitor {
  256. public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .utility)
  257. let monitors: [EventMonitor]
  258. init(monitors: [EventMonitor]) {
  259. self.monitors = monitors
  260. }
  261. func performEvent(_ event: @escaping (EventMonitor) -> Void) {
  262. queue.async {
  263. for monitor in self.monitors {
  264. monitor.queue.async { event(monitor) }
  265. }
  266. }
  267. }
  268. public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  269. performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) }
  270. }
  271. public func urlSession(_ session: URLSession,
  272. task: URLSessionTask,
  273. didReceive challenge: URLAuthenticationChallenge) {
  274. performEvent { $0.urlSession(session, task: task, didReceive: challenge) }
  275. }
  276. public func urlSession(_ session: URLSession,
  277. task: URLSessionTask,
  278. didSendBodyData bytesSent: Int64,
  279. totalBytesSent: Int64,
  280. totalBytesExpectedToSend: Int64) {
  281. performEvent {
  282. $0.urlSession(session,
  283. task: task,
  284. didSendBodyData: bytesSent,
  285. totalBytesSent: totalBytesSent,
  286. totalBytesExpectedToSend: totalBytesExpectedToSend)
  287. }
  288. }
  289. public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
  290. performEvent {
  291. $0.urlSession(session, taskNeedsNewBodyStream: task)
  292. }
  293. }
  294. public func urlSession(_ session: URLSession,
  295. task: URLSessionTask,
  296. willPerformHTTPRedirection response: HTTPURLResponse,
  297. newRequest request: URLRequest) {
  298. performEvent {
  299. $0.urlSession(session,
  300. task: task,
  301. willPerformHTTPRedirection: response,
  302. newRequest: request)
  303. }
  304. }
  305. public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  306. performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) }
  307. }
  308. public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  309. performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) }
  310. }
  311. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  312. public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  313. performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) }
  314. }
  315. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {
  316. performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: response) }
  317. }
  318. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  319. performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) }
  320. }
  321. public func urlSession(_ session: URLSession,
  322. dataTask: URLSessionDataTask,
  323. willCacheResponse proposedResponse: CachedURLResponse) {
  324. performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) }
  325. }
  326. public func urlSession(_ session: URLSession,
  327. downloadTask: URLSessionDownloadTask,
  328. didResumeAtOffset fileOffset: Int64,
  329. expectedTotalBytes: Int64) {
  330. performEvent {
  331. $0.urlSession(session,
  332. downloadTask: downloadTask,
  333. didResumeAtOffset: fileOffset,
  334. expectedTotalBytes: expectedTotalBytes)
  335. }
  336. }
  337. public func urlSession(_ session: URLSession,
  338. downloadTask: URLSessionDownloadTask,
  339. didWriteData bytesWritten: Int64,
  340. totalBytesWritten: Int64,
  341. totalBytesExpectedToWrite: Int64) {
  342. performEvent {
  343. $0.urlSession(session,
  344. downloadTask: downloadTask,
  345. didWriteData: bytesWritten,
  346. totalBytesWritten: totalBytesWritten,
  347. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  348. }
  349. }
  350. public func urlSession(_ session: URLSession,
  351. downloadTask: URLSessionDownloadTask,
  352. didFinishDownloadingTo location: URL) {
  353. performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) }
  354. }
  355. public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {
  356. performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) }
  357. }
  358. public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {
  359. performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) }
  360. }
  361. public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  362. performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) }
  363. }
  364. public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) {
  365. performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) }
  366. }
  367. public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
  368. performEvent { $0.request(request, didCreateURLRequest: urlRequest) }
  369. }
  370. public func request(_ request: Request, didCreateTask task: URLSessionTask) {
  371. performEvent { $0.request(request, didCreateTask: task) }
  372. }
  373. public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
  374. performEvent { $0.request(request, didGatherMetrics: metrics) }
  375. }
  376. public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {
  377. performEvent { $0.request(request, didFailTask: task, earlyWithError: error) }
  378. }
  379. public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
  380. performEvent { $0.request(request, didCompleteTask: task, with: error) }
  381. }
  382. public func requestIsRetrying(_ request: Request) {
  383. performEvent { $0.requestIsRetrying(request) }
  384. }
  385. public func requestDidFinish(_ request: Request) {
  386. performEvent { $0.requestDidFinish(request) }
  387. }
  388. public func requestDidResume(_ request: Request) {
  389. performEvent { $0.requestDidResume(request) }
  390. }
  391. public func request(_ request: Request, didResumeTask task: URLSessionTask) {
  392. performEvent { $0.request(request, didResumeTask: task) }
  393. }
  394. public func requestDidSuspend(_ request: Request) {
  395. performEvent { $0.requestDidSuspend(request) }
  396. }
  397. public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
  398. performEvent { $0.request(request, didSuspendTask: task) }
  399. }
  400. public func requestDidCancel(_ request: Request) {
  401. performEvent { $0.requestDidCancel(request) }
  402. }
  403. public func request(_ request: Request, didCancelTask task: URLSessionTask) {
  404. performEvent { $0.request(request, didCancelTask: task) }
  405. }
  406. public func request(_ request: DataRequest,
  407. didValidateRequest urlRequest: URLRequest?,
  408. response: HTTPURLResponse,
  409. data: Data?,
  410. withResult result: Request.ValidationResult) {
  411. performEvent { $0.request(request,
  412. didValidateRequest: urlRequest,
  413. response: response,
  414. data: data,
  415. withResult: result)
  416. }
  417. }
  418. public func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>) {
  419. performEvent { $0.request(request, didParseResponse: response) }
  420. }
  421. public func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {
  422. performEvent { $0.request(request, didParseResponse: response) }
  423. }
  424. public func request(_ request: DataStreamRequest,
  425. didValidateRequest urlRequest: URLRequest?,
  426. response: HTTPURLResponse,
  427. withResult result: Request.ValidationResult) {
  428. performEvent { $0.request(request,
  429. didValidateRequest: urlRequest,
  430. response: response,
  431. withResult: result)
  432. }
  433. }
  434. public func request<Value>(_ request: DataStreamRequest, didParseStream result: Result<Value, AFError>) {
  435. performEvent { $0.request(request, didParseStream: result) }
  436. }
  437. public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
  438. performEvent { $0.request(request, didCreateUploadable: uploadable) }
  439. }
  440. public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {
  441. performEvent { $0.request(request, didFailToCreateUploadableWithError: error) }
  442. }
  443. public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
  444. performEvent { $0.request(request, didProvideInputStream: stream) }
  445. }
  446. public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>) {
  447. performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) }
  448. }
  449. public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
  450. performEvent { $0.request(request, didCreateDestinationURL: url) }
  451. }
  452. public func request(_ request: DownloadRequest,
  453. didValidateRequest urlRequest: URLRequest?,
  454. response: HTTPURLResponse,
  455. fileURL: URL?,
  456. withResult result: Request.ValidationResult) {
  457. performEvent { $0.request(request,
  458. didValidateRequest: urlRequest,
  459. response: response,
  460. fileURL: fileURL,
  461. withResult: result) }
  462. }
  463. public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>) {
  464. performEvent { $0.request(request, didParseResponse: response) }
  465. }
  466. public func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value, AFError>) {
  467. performEvent { $0.request(request, didParseResponse: response) }
  468. }
  469. }
  470. /// `EventMonitor` that allows optional closures to be set to receive events.
  471. open class ClosureEventMonitor: EventMonitor {
  472. /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event.
  473. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
  474. /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`.
  475. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)?
  476. /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event.
  477. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
  478. /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event.
  479. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)?
  480. /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event.
  481. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)?
  482. /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event.
  483. open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)?
  484. /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event.
  485. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
  486. /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event.
  487. open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)?
  488. /// Closure called on the `urlSession(_:dataTask:didReceive:completionHandler:)` event.
  489. open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> Void)?
  490. /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event.
  491. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
  492. /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event.
  493. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)?
  494. /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event.
  495. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
  496. /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`
  497. /// event.
  498. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  499. /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event.
  500. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
  501. // MARK: - Request Events
  502. /// Closure called on the `request(_:didCreateInitialURLRequest:)` event.
  503. open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)?
  504. /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event.
  505. open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)?
  506. /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event.
  507. open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)?
  508. /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event.
  509. open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)?
  510. /// Closure called on the `request(_:didCreateURLRequest:)` event.
  511. open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)?
  512. /// Closure called on the `request(_:didCreateTask:)` event.
  513. open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)?
  514. /// Closure called on the `request(_:didGatherMetrics:)` event.
  515. open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)?
  516. /// Closure called on the `request(_:didFailTask:earlyWithError:)` event.
  517. open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)?
  518. /// Closure called on the `request(_:didCompleteTask:with:)` event.
  519. open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)?
  520. /// Closure called on the `requestIsRetrying(_:)` event.
  521. open var requestIsRetrying: ((Request) -> Void)?
  522. /// Closure called on the `requestDidFinish(_:)` event.
  523. open var requestDidFinish: ((Request) -> Void)?
  524. /// Closure called on the `requestDidResume(_:)` event.
  525. open var requestDidResume: ((Request) -> Void)?
  526. /// Closure called on the `request(_:didResumeTask:)` event.
  527. open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)?
  528. /// Closure called on the `requestDidSuspend(_:)` event.
  529. open var requestDidSuspend: ((Request) -> Void)?
  530. /// Closure called on the `request(_:didSuspendTask:)` event.
  531. open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)?
  532. /// Closure called on the `requestDidCancel(_:)` event.
  533. open var requestDidCancel: ((Request) -> Void)?
  534. /// Closure called on the `request(_:didCancelTask:)` event.
  535. open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)?
  536. /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event.
  537. open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)?
  538. /// Closure called on the `request(_:didParseResponse:)` event.
  539. open var requestDidParseResponse: ((DataRequest, DataResponse<Data?, AFError>) -> Void)?
  540. /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event.
  541. open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)?
  542. /// Closure called on the `request(_:didCreateUploadable:)` event.
  543. open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)?
  544. /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event.
  545. open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)?
  546. /// Closure called on the `request(_:didProvideInputStream:)` event.
  547. open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)?
  548. /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event.
  549. open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result<URL, AFError>) -> Void)?
  550. /// Closure called on the `request(_:didCreateDestinationURL:)` event.
  551. open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)?
  552. /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event.
  553. open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)?
  554. /// Closure called on the `request(_:didParseResponse:)` event.
  555. open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse<URL?, AFError>) -> Void)?
  556. public let queue: DispatchQueue
  557. /// Creates an instance using the provided queue.
  558. ///
  559. /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default.
  560. public init(queue: DispatchQueue = .main) {
  561. self.queue = queue
  562. }
  563. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  564. sessionDidBecomeInvalidWithError?(session, error)
  565. }
  566. open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) {
  567. taskDidReceiveChallenge?(session, task, challenge)
  568. }
  569. open func urlSession(_ session: URLSession,
  570. task: URLSessionTask,
  571. didSendBodyData bytesSent: Int64,
  572. totalBytesSent: Int64,
  573. totalBytesExpectedToSend: Int64) {
  574. taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
  575. }
  576. open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
  577. taskNeedNewBodyStream?(session, task)
  578. }
  579. open func urlSession(_ session: URLSession,
  580. task: URLSessionTask,
  581. willPerformHTTPRedirection response: HTTPURLResponse,
  582. newRequest request: URLRequest) {
  583. taskWillPerformHTTPRedirection?(session, task, response, request)
  584. }
  585. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  586. taskDidFinishCollectingMetrics?(session, task, metrics)
  587. }
  588. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  589. taskDidComplete?(session, task, error)
  590. }
  591. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  592. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  593. taskIsWaitingForConnectivity?(session, task)
  594. }
  595. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {
  596. dataTaskDidReceiveResponse?(session, dataTask, response)
  597. }
  598. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  599. dataTaskDidReceiveData?(session, dataTask, data)
  600. }
  601. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) {
  602. dataTaskWillCacheResponse?(session, dataTask, proposedResponse)
  603. }
  604. open func urlSession(_ session: URLSession,
  605. downloadTask: URLSessionDownloadTask,
  606. didResumeAtOffset fileOffset: Int64,
  607. expectedTotalBytes: Int64) {
  608. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  609. }
  610. open func urlSession(_ session: URLSession,
  611. downloadTask: URLSessionDownloadTask,
  612. didWriteData bytesWritten: Int64,
  613. totalBytesWritten: Int64,
  614. totalBytesExpectedToWrite: Int64) {
  615. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  616. }
  617. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  618. downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
  619. }
  620. // MARK: Request Events
  621. open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {
  622. requestDidCreateInitialURLRequest?(request, urlRequest)
  623. }
  624. open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {
  625. requestDidFailToCreateURLRequestWithError?(request, error)
  626. }
  627. open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  628. requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest)
  629. }
  630. open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) {
  631. requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error)
  632. }
  633. open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
  634. requestDidCreateURLRequest?(request, urlRequest)
  635. }
  636. open func request(_ request: Request, didCreateTask task: URLSessionTask) {
  637. requestDidCreateTask?(request, task)
  638. }
  639. open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
  640. requestDidGatherMetrics?(request, metrics)
  641. }
  642. open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {
  643. requestDidFailTaskEarlyWithError?(request, task, error)
  644. }
  645. open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
  646. requestDidCompleteTaskWithError?(request, task, error)
  647. }
  648. open func requestIsRetrying(_ request: Request) {
  649. requestIsRetrying?(request)
  650. }
  651. open func requestDidFinish(_ request: Request) {
  652. requestDidFinish?(request)
  653. }
  654. open func requestDidResume(_ request: Request) {
  655. requestDidResume?(request)
  656. }
  657. public func request(_ request: Request, didResumeTask task: URLSessionTask) {
  658. requestDidResumeTask?(request, task)
  659. }
  660. open func requestDidSuspend(_ request: Request) {
  661. requestDidSuspend?(request)
  662. }
  663. public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
  664. requestDidSuspendTask?(request, task)
  665. }
  666. open func requestDidCancel(_ request: Request) {
  667. requestDidCancel?(request)
  668. }
  669. public func request(_ request: Request, didCancelTask task: URLSessionTask) {
  670. requestDidCancelTask?(request, task)
  671. }
  672. open func request(_ request: DataRequest,
  673. didValidateRequest urlRequest: URLRequest?,
  674. response: HTTPURLResponse,
  675. data: Data?,
  676. withResult result: Request.ValidationResult) {
  677. requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result)
  678. }
  679. open func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>) {
  680. requestDidParseResponse?(request, response)
  681. }
  682. public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) {
  683. requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result)
  684. }
  685. open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
  686. requestDidCreateUploadable?(request, uploadable)
  687. }
  688. open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {
  689. requestDidFailToCreateUploadableWithError?(request, error)
  690. }
  691. open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
  692. requestDidProvideInputStream?(request, stream)
  693. }
  694. open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>) {
  695. requestDidFinishDownloadingUsingTaskWithResult?(request, task, result)
  696. }
  697. open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
  698. requestDidCreateDestinationURL?(request, url)
  699. }
  700. open func request(_ request: DownloadRequest,
  701. didValidateRequest urlRequest: URLRequest?,
  702. response: HTTPURLResponse,
  703. fileURL: URL?,
  704. withResult result: Request.ValidationResult) {
  705. requestDidValidateRequestResponseFileURLWithResult?(request,
  706. urlRequest,
  707. response,
  708. fileURL,
  709. result)
  710. }
  711. open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>) {
  712. requestDidParseDownloadResponse?(request, response)
  713. }
  714. }