ResponseSerialization.swift 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. //
  2. // ResponseSerialization.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. // MARK: Protocols
  26. /// The type to which all data response serializers must conform in order to serialize a response.
  27. public protocol DataResponseSerializerProtocol {
  28. /// The type of serialized object to be created.
  29. associatedtype SerializedObject
  30. /// Serialize the response `Data` into the provided type..
  31. ///
  32. /// - Parameters:
  33. /// - request: `URLRequest` which was used to perform the request, if any.
  34. /// - response: `HTTPURLResponse` received from the server, if any.
  35. /// - data: `Data` returned from the server, if any.
  36. /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
  37. ///
  38. /// - Returns: The `SerializedObject`.
  39. /// - Throws: Any `Error` produced during serialization.
  40. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
  41. }
  42. /// The type to which all download response serializers must conform in order to serialize a response.
  43. public protocol DownloadResponseSerializerProtocol {
  44. /// The type of serialized object to be created.
  45. associatedtype SerializedObject
  46. /// Serialize the downloaded response `Data` from disk into the provided type..
  47. ///
  48. /// - Parameters:
  49. /// - request: `URLRequest` which was used to perform the request, if any.
  50. /// - response: `HTTPURLResponse` received from the server, if any.
  51. /// - fileURL: File `URL` to which the response data was downloaded.
  52. /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
  53. ///
  54. /// - Returns: The `SerializedObject`.
  55. /// - Throws: Any `Error` produced during serialization.
  56. func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
  57. }
  58. /// A serializer that can handle both data and download responses.
  59. public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
  60. /// `DataPreprocessor` used to prepare incoming `Data` for serialization.
  61. var dataPreprocessor: DataPreprocessor { get }
  62. /// `HTTPMethod`s for which empty response bodies are considered appropriate.
  63. var emptyRequestMethods: Set<HTTPMethod> { get }
  64. /// HTTP response codes for which empty response bodies are considered appropriate.
  65. var emptyResponseCodes: Set<Int> { get }
  66. }
  67. /// Type used to preprocess `Data` before it handled by a serializer.
  68. public protocol DataPreprocessor {
  69. /// Process `Data` before it's handled by a serializer.
  70. /// - Parameter data: The raw `Data` to process.
  71. func preprocess(_ data: Data) throws -> Data
  72. }
  73. /// `DataPreprocessor` that returns passed `Data` without any transform.
  74. public struct PassthroughPreprocessor: DataPreprocessor {
  75. public init() {}
  76. public func preprocess(_ data: Data) throws -> Data { data }
  77. }
  78. /// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header.
  79. public struct GoogleXSSIPreprocessor: DataPreprocessor {
  80. public init() {}
  81. public func preprocess(_ data: Data) throws -> Data {
  82. (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data
  83. }
  84. }
  85. extension ResponseSerializer {
  86. /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default.
  87. public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() }
  88. /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default.
  89. public static var defaultEmptyRequestMethods: Set<HTTPMethod> { [.head] }
  90. /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default.
  91. public static var defaultEmptyResponseCodes: Set<Int> { [204, 205] }
  92. public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor }
  93. public var emptyRequestMethods: Set<HTTPMethod> { Self.defaultEmptyRequestMethods }
  94. public var emptyResponseCodes: Set<Int> { Self.defaultEmptyResponseCodes }
  95. /// Determines whether the `request` allows empty response bodies, if `request` exists.
  96. ///
  97. /// - Parameter request: `URLRequest` to evaluate.
  98. ///
  99. /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`.
  100. public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
  101. request.flatMap { $0.httpMethod }
  102. .flatMap(HTTPMethod.init)
  103. .map { emptyRequestMethods.contains($0) }
  104. }
  105. /// Determines whether the `response` allows empty response bodies, if `response` exists`.
  106. ///
  107. /// - Parameter response: `HTTPURLResponse` to evaluate.
  108. ///
  109. /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`.
  110. public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
  111. response.flatMap { $0.statusCode }
  112. .map { emptyResponseCodes.contains($0) }
  113. }
  114. /// Determines whether `request` and `response` allow empty response bodies.
  115. ///
  116. /// - Parameters:
  117. /// - request: `URLRequest` to evaluate.
  118. /// - response: `HTTPURLResponse` to evaluate.
  119. ///
  120. /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise.
  121. public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
  122. (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
  123. }
  124. }
  125. /// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
  126. /// the data read from disk into the data response serializer.
  127. extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
  128. public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
  129. guard error == nil else { throw error! }
  130. guard let fileURL = fileURL else {
  131. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  132. }
  133. let data: Data
  134. do {
  135. data = try Data(contentsOf: fileURL)
  136. } catch {
  137. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  138. }
  139. do {
  140. return try serialize(request: request, response: response, data: data, error: error)
  141. } catch {
  142. throw error
  143. }
  144. }
  145. }
  146. // MARK: - Default
  147. extension DataRequest {
  148. /// Adds a handler to be called once the request has finished.
  149. ///
  150. /// - Parameters:
  151. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  152. /// - completionHandler: The code to be executed once the request has finished.
  153. ///
  154. /// - Returns: The request.
  155. @discardableResult
  156. public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self {
  157. appendResponseSerializer {
  158. // Start work that should be on the serialization queue.
  159. let result = AFResult<Data?>(value: self.data, error: self.error)
  160. // End work that should be on the serialization queue.
  161. self.underlyingQueue.async {
  162. let response = DataResponse(request: self.request,
  163. response: self.response,
  164. data: self.data,
  165. metrics: self.metrics,
  166. serializationDuration: 0,
  167. result: result)
  168. self.eventMonitor?.request(self, didParseResponse: response)
  169. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  170. }
  171. }
  172. return self
  173. }
  174. /// Adds a handler to be called once the request has finished.
  175. ///
  176. /// - Parameters:
  177. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  178. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  179. /// - completionHandler: The code to be executed once the request has finished.
  180. ///
  181. /// - Returns: The request.
  182. @discardableResult
  183. public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  184. responseSerializer: Serializer,
  185. completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
  186. -> Self {
  187. appendResponseSerializer {
  188. // Start work that should be on the serialization queue.
  189. let start = ProcessInfo.processInfo.systemUptime
  190. let result: AFResult<Serializer.SerializedObject> = Result {
  191. try responseSerializer.serialize(request: self.request,
  192. response: self.response,
  193. data: self.data,
  194. error: self.error)
  195. }.mapError { error in
  196. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  197. }
  198. let end = ProcessInfo.processInfo.systemUptime
  199. // End work that should be on the serialization queue.
  200. self.underlyingQueue.async {
  201. let response = DataResponse(request: self.request,
  202. response: self.response,
  203. data: self.data,
  204. metrics: self.metrics,
  205. serializationDuration: end - start,
  206. result: result)
  207. self.eventMonitor?.request(self, didParseResponse: response)
  208. guard let serializerError = result.failure, let delegate = self.delegate else {
  209. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  210. return
  211. }
  212. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  213. var didComplete: (() -> Void)?
  214. defer {
  215. if let didComplete = didComplete {
  216. self.responseSerializerDidComplete { queue.async { didComplete() } }
  217. }
  218. }
  219. switch retryResult {
  220. case .doNotRetry:
  221. didComplete = { completionHandler(response) }
  222. case let .doNotRetryWithError(retryError):
  223. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  224. let response = DataResponse(request: self.request,
  225. response: self.response,
  226. data: self.data,
  227. metrics: self.metrics,
  228. serializationDuration: end - start,
  229. result: result)
  230. didComplete = { completionHandler(response) }
  231. case .retry, .retryWithDelay:
  232. delegate.retryRequest(self, withDelay: retryResult.delay)
  233. }
  234. }
  235. }
  236. }
  237. return self
  238. }
  239. }
  240. extension DownloadRequest {
  241. /// Adds a handler to be called once the request has finished.
  242. ///
  243. /// - Parameters:
  244. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  245. /// - completionHandler: The code to be executed once the request has finished.
  246. ///
  247. /// - Returns: The request.
  248. @discardableResult
  249. public func response(queue: DispatchQueue = .main,
  250. completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
  251. -> Self {
  252. appendResponseSerializer {
  253. // Start work that should be on the serialization queue.
  254. let result = AFResult<URL?>(value: self.fileURL, error: self.error)
  255. // End work that should be on the serialization queue.
  256. self.underlyingQueue.async {
  257. let response = DownloadResponse(request: self.request,
  258. response: self.response,
  259. fileURL: self.fileURL,
  260. resumeData: self.resumeData,
  261. metrics: self.metrics,
  262. serializationDuration: 0,
  263. result: result)
  264. self.eventMonitor?.request(self, didParseResponse: response)
  265. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  266. }
  267. }
  268. return self
  269. }
  270. /// Adds a handler to be called once the request has finished.
  271. ///
  272. /// - Parameters:
  273. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  274. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  275. /// contained in the destination `URL`.
  276. /// - completionHandler: The code to be executed once the request has finished.
  277. ///
  278. /// - Returns: The request.
  279. @discardableResult
  280. public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
  281. responseSerializer: Serializer,
  282. completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  283. -> Self {
  284. appendResponseSerializer {
  285. // Start work that should be on the serialization queue.
  286. let start = ProcessInfo.processInfo.systemUptime
  287. let result: AFResult<Serializer.SerializedObject> = Result {
  288. try responseSerializer.serializeDownload(request: self.request,
  289. response: self.response,
  290. fileURL: self.fileURL,
  291. error: self.error)
  292. }.mapError { error in
  293. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  294. }
  295. let end = ProcessInfo.processInfo.systemUptime
  296. // End work that should be on the serialization queue.
  297. self.underlyingQueue.async {
  298. let response = DownloadResponse(request: self.request,
  299. response: self.response,
  300. fileURL: self.fileURL,
  301. resumeData: self.resumeData,
  302. metrics: self.metrics,
  303. serializationDuration: end - start,
  304. result: result)
  305. self.eventMonitor?.request(self, didParseResponse: response)
  306. guard let serializerError = result.failure, let delegate = self.delegate else {
  307. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  308. return
  309. }
  310. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  311. var didComplete: (() -> Void)?
  312. defer {
  313. if let didComplete = didComplete {
  314. self.responseSerializerDidComplete { queue.async { didComplete() } }
  315. }
  316. }
  317. switch retryResult {
  318. case .doNotRetry:
  319. didComplete = { completionHandler(response) }
  320. case let .doNotRetryWithError(retryError):
  321. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  322. let response = DownloadResponse(request: self.request,
  323. response: self.response,
  324. fileURL: self.fileURL,
  325. resumeData: self.resumeData,
  326. metrics: self.metrics,
  327. serializationDuration: end - start,
  328. result: result)
  329. didComplete = { completionHandler(response) }
  330. case .retry, .retryWithDelay:
  331. delegate.retryRequest(self, withDelay: retryResult.delay)
  332. }
  333. }
  334. }
  335. }
  336. return self
  337. }
  338. }
  339. // MARK: - URL
  340. /// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL`
  341. /// is present.
  342. public struct URLResponseSerializer: DownloadResponseSerializerProtocol {
  343. /// Creates an instance.
  344. public init() {}
  345. public func serializeDownload(request: URLRequest?,
  346. response: HTTPURLResponse?,
  347. fileURL: URL?,
  348. error: Error?) throws -> URL {
  349. guard error == nil else { throw error! }
  350. guard let url = fileURL else {
  351. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  352. }
  353. return url
  354. }
  355. }
  356. extension DownloadRequest {
  357. /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished.
  358. ///
  359. /// - Parameters:
  360. /// - queue: The queue on which the completion handler is called. `.main` by default.
  361. /// - completionHandler: A closure to be executed once the request has finished.
  362. ///
  363. /// - Returns: The request.
  364. @discardableResult
  365. public func responseURL(queue: DispatchQueue = .main,
  366. completionHandler: @escaping (AFDownloadResponse<URL>) -> Void) -> Self {
  367. response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler)
  368. }
  369. }
  370. // MARK: - Data
  371. /// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a
  372. /// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the
  373. /// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned.
  374. public final class DataResponseSerializer: ResponseSerializer {
  375. public let dataPreprocessor: DataPreprocessor
  376. public let emptyResponseCodes: Set<Int>
  377. public let emptyRequestMethods: Set<HTTPMethod>
  378. /// Creates an instance using the provided values.
  379. ///
  380. /// - Parameters:
  381. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  382. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  383. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  384. public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  385. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  386. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
  387. self.dataPreprocessor = dataPreprocessor
  388. self.emptyResponseCodes = emptyResponseCodes
  389. self.emptyRequestMethods = emptyRequestMethods
  390. }
  391. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
  392. guard error == nil else { throw error! }
  393. guard var data = data, !data.isEmpty else {
  394. guard emptyResponseAllowed(forRequest: request, response: response) else {
  395. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  396. }
  397. return Data()
  398. }
  399. data = try dataPreprocessor.preprocess(data)
  400. return data
  401. }
  402. }
  403. extension DataRequest {
  404. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  405. ///
  406. /// - Parameters:
  407. /// - queue: The queue on which the completion handler is called. `.main` by default.
  408. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  409. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  410. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  411. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  412. /// - completionHandler: A closure to be executed once the request has finished.
  413. ///
  414. /// - Returns: The request.
  415. @discardableResult
  416. public func responseData(queue: DispatchQueue = .main,
  417. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  418. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  419. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  420. completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self {
  421. response(queue: queue,
  422. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  423. emptyResponseCodes: emptyResponseCodes,
  424. emptyRequestMethods: emptyRequestMethods),
  425. completionHandler: completionHandler)
  426. }
  427. }
  428. extension DownloadRequest {
  429. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  430. ///
  431. /// - Parameters:
  432. /// - queue: The queue on which the completion handler is called. `.main` by default.
  433. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  434. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  435. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  436. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  437. /// - completionHandler: A closure to be executed once the request has finished.
  438. ///
  439. /// - Returns: The request.
  440. @discardableResult
  441. public func responseData(queue: DispatchQueue = .main,
  442. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  443. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  444. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  445. completionHandler: @escaping (AFDownloadResponse<Data>) -> Void) -> Self {
  446. response(queue: queue,
  447. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  448. emptyResponseCodes: emptyResponseCodes,
  449. emptyRequestMethods: emptyRequestMethods),
  450. completionHandler: completionHandler)
  451. }
  452. }
  453. // MARK: - String
  454. /// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
  455. /// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code
  456. /// valid for empty responses, then an empty `String` is returned.
  457. public final class StringResponseSerializer: ResponseSerializer {
  458. public let dataPreprocessor: DataPreprocessor
  459. /// Optional string encoding used to validate the response.
  460. public let encoding: String.Encoding?
  461. public let emptyResponseCodes: Set<Int>
  462. public let emptyRequestMethods: Set<HTTPMethod>
  463. /// Creates an instance with the provided values.
  464. ///
  465. /// - Parameters:
  466. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  467. /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined
  468. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  469. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  470. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  471. public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  472. encoding: String.Encoding? = nil,
  473. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  474. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
  475. self.dataPreprocessor = dataPreprocessor
  476. self.encoding = encoding
  477. self.emptyResponseCodes = emptyResponseCodes
  478. self.emptyRequestMethods = emptyRequestMethods
  479. }
  480. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
  481. guard error == nil else { throw error! }
  482. guard var data = data, !data.isEmpty else {
  483. guard emptyResponseAllowed(forRequest: request, response: response) else {
  484. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  485. }
  486. return ""
  487. }
  488. data = try dataPreprocessor.preprocess(data)
  489. var convertedEncoding = encoding
  490. if let encodingName = response?.textEncodingName, convertedEncoding == nil {
  491. convertedEncoding = String.Encoding(ianaCharsetName: encodingName)
  492. }
  493. let actualEncoding = convertedEncoding ?? .isoLatin1
  494. guard let string = String(data: data, encoding: actualEncoding) else {
  495. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  496. }
  497. return string
  498. }
  499. }
  500. extension DataRequest {
  501. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  502. ///
  503. /// - Parameters:
  504. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  505. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  506. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  507. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  508. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  509. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  510. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  511. /// - completionHandler: A closure to be executed once the request has finished.
  512. ///
  513. /// - Returns: The request.
  514. @discardableResult
  515. public func responseString(queue: DispatchQueue = .main,
  516. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  517. encoding: String.Encoding? = nil,
  518. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  519. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  520. completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
  521. response(queue: queue,
  522. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  523. encoding: encoding,
  524. emptyResponseCodes: emptyResponseCodes,
  525. emptyRequestMethods: emptyRequestMethods),
  526. completionHandler: completionHandler)
  527. }
  528. }
  529. extension DownloadRequest {
  530. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  531. ///
  532. /// - Parameters:
  533. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  534. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  535. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  536. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  537. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  538. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  539. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  540. /// - completionHandler: A closure to be executed once the request has finished.
  541. ///
  542. /// - Returns: The request.
  543. @discardableResult
  544. public func responseString(queue: DispatchQueue = .main,
  545. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  546. encoding: String.Encoding? = nil,
  547. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  548. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  549. completionHandler: @escaping (AFDownloadResponse<String>) -> Void) -> Self {
  550. response(queue: queue,
  551. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  552. encoding: encoding,
  553. emptyResponseCodes: emptyResponseCodes,
  554. emptyRequestMethods: emptyRequestMethods),
  555. completionHandler: completionHandler)
  556. }
  557. }
  558. // MARK: - JSON
  559. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  560. /// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an
  561. /// HTTP status code valid for empty responses, then an `NSNull` value is returned.
  562. public final class JSONResponseSerializer: ResponseSerializer {
  563. public let dataPreprocessor: DataPreprocessor
  564. public let emptyResponseCodes: Set<Int>
  565. public let emptyRequestMethods: Set<HTTPMethod>
  566. /// `JSONSerialization.ReadingOptions` used when serializing a response.
  567. public let options: JSONSerialization.ReadingOptions
  568. /// Creates an instance with the provided values.
  569. ///
  570. /// - Parameters:
  571. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  572. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  573. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  574. /// - options: The options to use. `.allowFragments` by default.
  575. public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  576. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  577. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  578. options: JSONSerialization.ReadingOptions = .allowFragments) {
  579. self.dataPreprocessor = dataPreprocessor
  580. self.emptyResponseCodes = emptyResponseCodes
  581. self.emptyRequestMethods = emptyRequestMethods
  582. self.options = options
  583. }
  584. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  585. guard error == nil else { throw error! }
  586. guard var data = data, !data.isEmpty else {
  587. guard emptyResponseAllowed(forRequest: request, response: response) else {
  588. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  589. }
  590. return NSNull()
  591. }
  592. data = try dataPreprocessor.preprocess(data)
  593. do {
  594. return try JSONSerialization.jsonObject(with: data, options: options)
  595. } catch {
  596. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  597. }
  598. }
  599. }
  600. extension DataRequest {
  601. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  602. ///
  603. /// - Parameters:
  604. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  605. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  606. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  607. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  608. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  609. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  610. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  611. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  612. /// by default.
  613. /// - completionHandler: A closure to be executed once the request has finished.
  614. ///
  615. /// - Returns: The request.
  616. @discardableResult
  617. public func responseJSON(queue: DispatchQueue = .main,
  618. dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  619. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  620. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  621. options: JSONSerialization.ReadingOptions = .allowFragments,
  622. completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
  623. response(queue: queue,
  624. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  625. emptyResponseCodes: emptyResponseCodes,
  626. emptyRequestMethods: emptyRequestMethods,
  627. options: options),
  628. completionHandler: completionHandler)
  629. }
  630. }
  631. extension DownloadRequest {
  632. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  633. ///
  634. /// - Parameters:
  635. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  636. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  637. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  638. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  639. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  640. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  641. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  642. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  643. /// by default.
  644. /// - completionHandler: A closure to be executed once the request has finished.
  645. ///
  646. /// - Returns: The request.
  647. @discardableResult
  648. public func responseJSON(queue: DispatchQueue = .main,
  649. dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  650. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  651. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  652. options: JSONSerialization.ReadingOptions = .allowFragments,
  653. completionHandler: @escaping (AFDownloadResponse<Any>) -> Void) -> Self {
  654. response(queue: queue,
  655. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  656. emptyResponseCodes: emptyResponseCodes,
  657. emptyRequestMethods: emptyRequestMethods,
  658. options: options),
  659. completionHandler: completionHandler)
  660. }
  661. }
  662. // MARK: - Empty
  663. /// Protocol representing an empty response. Use `T.emptyValue()` to get an instance.
  664. public protocol EmptyResponse {
  665. /// Empty value for the conforming type.
  666. ///
  667. /// - Returns: Value of `Self` to use for empty values.
  668. static func emptyValue() -> Self
  669. }
  670. /// Type representing an empty value. Use `Empty.value` to get the static instance.
  671. public struct Empty: Codable {
  672. /// Static `Empty` instance used for all `Empty` responses.
  673. public static let value = Empty()
  674. }
  675. extension Empty: EmptyResponse {
  676. public static func emptyValue() -> Empty {
  677. value
  678. }
  679. }
  680. // MARK: - DataDecoder Protocol
  681. /// Any type which can decode `Data` into a `Decodable` type.
  682. public protocol DataDecoder {
  683. /// Decode `Data` into the provided type.
  684. ///
  685. /// - Parameters:
  686. /// - type: The `Type` to be decoded.
  687. /// - data: The `Data` to be decoded.
  688. ///
  689. /// - Returns: The decoded value of type `D`.
  690. /// - Throws: Any error that occurs during decode.
  691. func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
  692. }
  693. /// `JSONDecoder` automatically conforms to `DataDecoder`.
  694. extension JSONDecoder: DataDecoder {}
  695. /// `PropertyListDecoder` automatically conforms to `DataDecoder`.
  696. extension PropertyListDecoder: DataDecoder {}
  697. // MARK: - Decodable
  698. /// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
  699. /// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
  700. /// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid
  701. /// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the
  702. /// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the
  703. /// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced.
  704. public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  705. public let dataPreprocessor: DataPreprocessor
  706. /// The `DataDecoder` instance used to decode responses.
  707. public let decoder: DataDecoder
  708. public let emptyResponseCodes: Set<Int>
  709. public let emptyRequestMethods: Set<HTTPMethod>
  710. /// Creates an instance using the values provided.
  711. ///
  712. /// - Parameters:
  713. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  714. /// - decoder: The `DataDecoder`. `JSONDecoder()` by default.
  715. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  716. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  717. public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
  718. decoder: DataDecoder = JSONDecoder(),
  719. emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
  720. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
  721. self.dataPreprocessor = dataPreprocessor
  722. self.decoder = decoder
  723. self.emptyResponseCodes = emptyResponseCodes
  724. self.emptyRequestMethods = emptyRequestMethods
  725. }
  726. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  727. guard error == nil else { throw error! }
  728. guard var data = data, !data.isEmpty else {
  729. guard emptyResponseAllowed(forRequest: request, response: response) else {
  730. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  731. }
  732. guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
  733. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  734. }
  735. return emptyValue
  736. }
  737. data = try dataPreprocessor.preprocess(data)
  738. do {
  739. return try decoder.decode(T.self, from: data)
  740. } catch {
  741. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  742. }
  743. }
  744. }
  745. extension DataRequest {
  746. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  747. ///
  748. /// - Parameters:
  749. /// - type: `Decodable` type to decode from response data.
  750. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  751. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  752. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  753. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  754. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  755. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  756. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  757. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  758. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  759. /// by default.
  760. /// - completionHandler: A closure to be executed once the request has finished.
  761. ///
  762. /// - Returns: The request.
  763. @discardableResult
  764. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  765. queue: DispatchQueue = .main,
  766. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  767. decoder: DataDecoder = JSONDecoder(),
  768. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  769. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  770. completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
  771. response(queue: queue,
  772. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  773. decoder: decoder,
  774. emptyResponseCodes: emptyResponseCodes,
  775. emptyRequestMethods: emptyRequestMethods),
  776. completionHandler: completionHandler)
  777. }
  778. }
  779. extension DownloadRequest {
  780. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  781. ///
  782. /// - Parameters:
  783. /// - type: `Decodable` type to decode from response data.
  784. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  785. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  786. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  787. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  788. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  789. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  790. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  791. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  792. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  793. /// by default.
  794. /// - completionHandler: A closure to be executed once the request has finished.
  795. ///
  796. /// - Returns: The request.
  797. @discardableResult
  798. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  799. queue: DispatchQueue = .main,
  800. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  801. decoder: DataDecoder = JSONDecoder(),
  802. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  803. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  804. completionHandler: @escaping (AFDownloadResponse<T>) -> Void) -> Self {
  805. response(queue: queue,
  806. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  807. decoder: decoder,
  808. emptyResponseCodes: emptyResponseCodes,
  809. emptyRequestMethods: emptyRequestMethods),
  810. completionHandler: completionHandler)
  811. }
  812. }
  813. // MARK: - DataStreamRequest
  814. /// A type which can serialize incoming `Data`.
  815. public protocol DataStreamSerializer {
  816. /// Type produced from the serialized `Data`.
  817. associatedtype SerializedObject
  818. /// Serializes incoming `Data` into a `SerializedObject` value.
  819. ///
  820. /// - Parameter data: `Data` to be serialized.
  821. ///
  822. /// - Throws: Any error produced during serialization.
  823. func serialize(_ data: Data) throws -> SerializedObject
  824. }
  825. /// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`.
  826. public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer {
  827. /// `DataDecoder` used to decode incoming `Data`.
  828. public let decoder: DataDecoder
  829. /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`.
  830. public let dataPreprocessor: DataPreprocessor
  831. /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`.
  832. /// - Parameters:
  833. /// - decoder: ` DataDecoder` used to decode incoming `Data`.
  834. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the `decoder`.
  835. public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) {
  836. self.decoder = decoder
  837. self.dataPreprocessor = dataPreprocessor
  838. }
  839. public func serialize(_ data: Data) throws -> T {
  840. let processedData = try dataPreprocessor.preprocess(data)
  841. do {
  842. return try decoder.decode(T.self, from: processedData)
  843. } catch {
  844. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  845. }
  846. }
  847. }
  848. /// `DataStreamSerializer` which performs no serialization on incoming `Data`.
  849. public struct PassthroughStreamSerializer: DataStreamSerializer {
  850. public func serialize(_ data: Data) throws -> Data { data }
  851. }
  852. /// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values.
  853. public struct StringStreamSerializer: DataStreamSerializer {
  854. public func serialize(_ data: Data) throws -> String {
  855. String(decoding: data, as: UTF8.self)
  856. }
  857. }
  858. extension DataStreamRequest {
  859. /// Adds a `StreamHandler` which performs no parsing on incoming `Data`.
  860. ///
  861. /// - Parameters:
  862. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  863. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  864. ///
  865. /// - Returns: The `DataStreamRequest`.
  866. @discardableResult
  867. public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
  868. let parser = { [unowned self] (data: Data) in
  869. queue.async {
  870. self.capturingError {
  871. try stream(.init(event: .stream(.success(data)), token: .init(self)))
  872. }
  873. self.updateAndCompleteIfPossible()
  874. }
  875. }
  876. $streamMutableState.write { $0.streams.append(parser) }
  877. appendStreamCompletion(on: queue, stream: stream)
  878. return self
  879. }
  880. /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`.
  881. ///
  882. /// - Parameters:
  883. /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`.
  884. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  885. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  886. ///
  887. /// - Returns: The `DataStreamRequest`.
  888. @discardableResult
  889. public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
  890. on queue: DispatchQueue = .main,
  891. stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
  892. let parser = { [unowned self] (data: Data) in
  893. self.serializationQueue.async {
  894. // Start work on serialization queue.
  895. let result = Result { try serializer.serialize(data) }
  896. .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
  897. // End work on serialization queue.
  898. self.underlyingQueue.async {
  899. self.eventMonitor?.request(self, didParseStream: result)
  900. if result.isFailure, self.automaticallyCancelOnStreamError {
  901. self.cancel()
  902. }
  903. queue.async {
  904. self.capturingError {
  905. try stream(.init(event: .stream(result), token: .init(self)))
  906. }
  907. self.updateAndCompleteIfPossible()
  908. }
  909. }
  910. }
  911. }
  912. $streamMutableState.write { $0.streams.append(parser) }
  913. appendStreamCompletion(on: queue, stream: stream)
  914. return self
  915. }
  916. /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`.
  917. ///
  918. /// - Parameters:
  919. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  920. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  921. ///
  922. /// - Returns: The `DataStreamRequest`.
  923. @discardableResult
  924. public func responseStreamString(on queue: DispatchQueue = .main,
  925. stream: @escaping Handler<String, Never>) -> Self {
  926. let parser = { [unowned self] (data: Data) in
  927. self.serializationQueue.async {
  928. // Start work on serialization queue.
  929. let string = String(decoding: data, as: UTF8.self)
  930. // End work on serialization queue.
  931. self.underlyingQueue.async {
  932. self.eventMonitor?.request(self, didParseStream: .success(string))
  933. queue.async {
  934. self.capturingError {
  935. try stream(.init(event: .stream(.success(string)), token: .init(self)))
  936. }
  937. self.updateAndCompleteIfPossible()
  938. }
  939. }
  940. }
  941. }
  942. $streamMutableState.write { $0.streams.append(parser) }
  943. appendStreamCompletion(on: queue, stream: stream)
  944. return self
  945. }
  946. private func updateAndCompleteIfPossible() {
  947. $streamMutableState.write { state in
  948. state.numberOfExecutingStreams -= 1
  949. guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return }
  950. let completionEvents = state.enqueuedCompletionEvents
  951. self.underlyingQueue.async { completionEvents.forEach { $0() } }
  952. state.enqueuedCompletionEvents.removeAll()
  953. }
  954. }
  955. /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`.
  956. ///
  957. /// - Parameters:
  958. /// - type: `Decodable` type to parse incoming `Data` into.
  959. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  960. /// - decoder: `DataDecoder` used to decode the incoming `Data`.
  961. /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`.
  962. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  963. ///
  964. /// - Returns: The `DataStreamRequest`.
  965. @discardableResult
  966. public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
  967. on queue: DispatchQueue = .main,
  968. using decoder: DataDecoder = JSONDecoder(),
  969. preprocessor: DataPreprocessor = PassthroughPreprocessor(),
  970. stream: @escaping Handler<T, AFError>) -> Self {
  971. responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
  972. stream: stream)
  973. }
  974. }