EventMonitor.swift 44 KB

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