ResponseSerialization.swift 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
  128. 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: - Data
  340. /// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a
  341. /// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the
  342. /// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned.
  343. public final class DataResponseSerializer: ResponseSerializer {
  344. public let dataPreprocessor: DataPreprocessor
  345. public let emptyResponseCodes: Set<Int>
  346. public let emptyRequestMethods: Set<HTTPMethod>
  347. /// Creates an instance using the provided values.
  348. ///
  349. /// - Parameters:
  350. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  351. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  352. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  353. public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  354. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  355. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
  356. self.dataPreprocessor = dataPreprocessor
  357. self.emptyResponseCodes = emptyResponseCodes
  358. self.emptyRequestMethods = emptyRequestMethods
  359. }
  360. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
  361. guard error == nil else { throw error! }
  362. guard var data = data, !data.isEmpty else {
  363. guard emptyResponseAllowed(forRequest: request, response: response) else {
  364. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  365. }
  366. return Data()
  367. }
  368. data = try dataPreprocessor.preprocess(data)
  369. return data
  370. }
  371. }
  372. extension DataRequest {
  373. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  374. ///
  375. /// - Parameters:
  376. /// - queue: The queue on which the completion handler is called. `.main` by default.
  377. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  378. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  379. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  380. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  381. /// - completionHandler: A closure to be executed once the request has finished.
  382. ///
  383. /// - Returns: The request.
  384. @discardableResult
  385. public func responseData(queue: DispatchQueue = .main,
  386. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  387. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  388. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  389. completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self {
  390. response(queue: queue,
  391. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  392. emptyResponseCodes: emptyResponseCodes,
  393. emptyRequestMethods: emptyRequestMethods),
  394. completionHandler: completionHandler)
  395. }
  396. }
  397. extension DownloadRequest {
  398. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  399. ///
  400. /// - Parameters:
  401. /// - queue: The queue on which the completion handler is called. `.main` by default.
  402. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  403. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  404. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  405. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  406. /// - completionHandler: A closure to be executed once the request has finished.
  407. ///
  408. /// - Returns: The request.
  409. @discardableResult
  410. public func responseData(queue: DispatchQueue = .main,
  411. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  412. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  413. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  414. completionHandler: @escaping (AFDownloadResponse<Data>) -> Void) -> Self {
  415. response(queue: queue,
  416. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  417. emptyResponseCodes: emptyResponseCodes,
  418. emptyRequestMethods: emptyRequestMethods),
  419. completionHandler: completionHandler)
  420. }
  421. }
  422. // MARK: - String
  423. /// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
  424. /// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code
  425. /// valid for empty responses, then an empty `String` is returned.
  426. public final class StringResponseSerializer: ResponseSerializer {
  427. public let dataPreprocessor: DataPreprocessor
  428. /// Optional string encoding used to validate the response.
  429. public let encoding: String.Encoding?
  430. public let emptyResponseCodes: Set<Int>
  431. public let emptyRequestMethods: Set<HTTPMethod>
  432. /// Creates an instance with the provided values.
  433. ///
  434. /// - Parameters:
  435. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  436. /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined
  437. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  438. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  439. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  440. public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  441. encoding: String.Encoding? = nil,
  442. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  443. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
  444. self.dataPreprocessor = dataPreprocessor
  445. self.encoding = encoding
  446. self.emptyResponseCodes = emptyResponseCodes
  447. self.emptyRequestMethods = emptyRequestMethods
  448. }
  449. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
  450. guard error == nil else { throw error! }
  451. guard var data = data, !data.isEmpty else {
  452. guard emptyResponseAllowed(forRequest: request, response: response) else {
  453. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  454. }
  455. return ""
  456. }
  457. data = try dataPreprocessor.preprocess(data)
  458. var convertedEncoding = encoding
  459. if let encodingName = response?.textEncodingName, convertedEncoding == nil {
  460. convertedEncoding = String.Encoding(ianaCharsetName: encodingName)
  461. }
  462. let actualEncoding = convertedEncoding ?? .isoLatin1
  463. guard let string = String(data: data, encoding: actualEncoding) else {
  464. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  465. }
  466. return string
  467. }
  468. }
  469. extension DataRequest {
  470. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  471. ///
  472. /// - Parameters:
  473. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  474. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  475. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  476. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  477. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  478. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  479. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  480. /// - completionHandler: A closure to be executed once the request has finished.
  481. ///
  482. /// - Returns: The request.
  483. @discardableResult
  484. public func responseString(queue: DispatchQueue = .main,
  485. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  486. encoding: String.Encoding? = nil,
  487. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  488. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  489. completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
  490. response(queue: queue,
  491. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  492. encoding: encoding,
  493. emptyResponseCodes: emptyResponseCodes,
  494. emptyRequestMethods: emptyRequestMethods),
  495. completionHandler: completionHandler)
  496. }
  497. }
  498. extension DownloadRequest {
  499. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  500. ///
  501. /// - Parameters:
  502. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  503. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  504. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  505. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  506. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  507. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  508. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  509. /// - completionHandler: A closure to be executed once the request has finished.
  510. ///
  511. /// - Returns: The request.
  512. @discardableResult
  513. public func responseString(queue: DispatchQueue = .main,
  514. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  515. encoding: String.Encoding? = nil,
  516. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  517. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  518. completionHandler: @escaping (AFDownloadResponse<String>) -> Void) -> Self {
  519. response(queue: queue,
  520. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  521. encoding: encoding,
  522. emptyResponseCodes: emptyResponseCodes,
  523. emptyRequestMethods: emptyRequestMethods),
  524. completionHandler: completionHandler)
  525. }
  526. }
  527. // MARK: - JSON
  528. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  529. /// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an
  530. /// HTTP status code valid for empty responses, then an `NSNull` value is returned.
  531. public final class JSONResponseSerializer: ResponseSerializer {
  532. public let dataPreprocessor: DataPreprocessor
  533. public let emptyResponseCodes: Set<Int>
  534. public let emptyRequestMethods: Set<HTTPMethod>
  535. /// `JSONSerialization.ReadingOptions` used when serializing a response.
  536. public let options: JSONSerialization.ReadingOptions
  537. /// Creates an instance with the provided values.
  538. ///
  539. /// - Parameters:
  540. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  541. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  542. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  543. /// - options: The options to use. `.allowFragments` by default.
  544. public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  545. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  546. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  547. options: JSONSerialization.ReadingOptions = .allowFragments) {
  548. self.dataPreprocessor = dataPreprocessor
  549. self.emptyResponseCodes = emptyResponseCodes
  550. self.emptyRequestMethods = emptyRequestMethods
  551. self.options = options
  552. }
  553. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  554. guard error == nil else { throw error! }
  555. guard var data = data, !data.isEmpty else {
  556. guard emptyResponseAllowed(forRequest: request, response: response) else {
  557. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  558. }
  559. return NSNull()
  560. }
  561. data = try dataPreprocessor.preprocess(data)
  562. do {
  563. return try JSONSerialization.jsonObject(with: data, options: options)
  564. } catch {
  565. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  566. }
  567. }
  568. }
  569. extension DataRequest {
  570. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  571. ///
  572. /// - Parameters:
  573. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  574. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  575. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  576. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  577. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  578. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  579. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  580. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  581. /// by default.
  582. /// - completionHandler: A closure to be executed once the request has finished.
  583. ///
  584. /// - Returns: The request.
  585. @discardableResult
  586. public func responseJSON(queue: DispatchQueue = .main,
  587. dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  588. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  589. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  590. options: JSONSerialization.ReadingOptions = .allowFragments,
  591. completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
  592. response(queue: queue,
  593. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  594. emptyResponseCodes: emptyResponseCodes,
  595. emptyRequestMethods: emptyRequestMethods,
  596. options: options),
  597. completionHandler: completionHandler)
  598. }
  599. }
  600. extension DownloadRequest {
  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 (AFDownloadResponse<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. // MARK: - Empty
  632. /// Protocol representing an empty response. Use `T.emptyValue()` to get an instance.
  633. public protocol EmptyResponse {
  634. /// Empty value for the conforming type.
  635. ///
  636. /// - Returns: Value of `Self` to use for empty values.
  637. static func emptyValue() -> Self
  638. }
  639. /// Type representing an empty value. Use `Empty.value` to get the static instance.
  640. public struct Empty: Codable {
  641. /// Static `Empty` instance used for all `Empty` responses.
  642. public static let value = Empty()
  643. }
  644. extension Empty: EmptyResponse {
  645. public static func emptyValue() -> Empty {
  646. value
  647. }
  648. }
  649. // MARK: - DataDecoder Protocol
  650. /// Any type which can decode `Data` into a `Decodable` type.
  651. public protocol DataDecoder {
  652. /// Decode `Data` into the provided type.
  653. ///
  654. /// - Parameters:
  655. /// - type: The `Type` to be decoded.
  656. /// - data: The `Data` to be decoded.
  657. ///
  658. /// - Returns: The decoded value of type `D`.
  659. /// - Throws: Any error that occurs during decode.
  660. func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
  661. }
  662. /// `JSONDecoder` automatically conforms to `DataDecoder`.
  663. extension JSONDecoder: DataDecoder {}
  664. /// `PropertyListDecoder` automatically conforms to `DataDecoder`.
  665. extension PropertyListDecoder: DataDecoder {}
  666. // MARK: - Decodable
  667. /// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
  668. /// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
  669. /// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid
  670. /// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the
  671. /// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the
  672. /// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced.
  673. public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  674. public let dataPreprocessor: DataPreprocessor
  675. /// The `DataDecoder` instance used to decode responses.
  676. public let decoder: DataDecoder
  677. public let emptyResponseCodes: Set<Int>
  678. public let emptyRequestMethods: Set<HTTPMethod>
  679. /// Creates an instance using the values provided.
  680. ///
  681. /// - Parameters:
  682. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  683. /// - decoder: The `DataDecoder`. `JSONDecoder()` by default.
  684. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  685. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  686. public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
  687. decoder: DataDecoder = JSONDecoder(),
  688. emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
  689. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
  690. self.dataPreprocessor = dataPreprocessor
  691. self.decoder = decoder
  692. self.emptyResponseCodes = emptyResponseCodes
  693. self.emptyRequestMethods = emptyRequestMethods
  694. }
  695. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  696. guard error == nil else { throw error! }
  697. guard var data = data, !data.isEmpty else {
  698. guard emptyResponseAllowed(forRequest: request, response: response) else {
  699. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  700. }
  701. guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
  702. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  703. }
  704. return emptyValue
  705. }
  706. data = try dataPreprocessor.preprocess(data)
  707. do {
  708. return try decoder.decode(T.self, from: data)
  709. } catch {
  710. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  711. }
  712. }
  713. }
  714. extension DataRequest {
  715. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  716. ///
  717. /// - Parameters:
  718. /// - type: `Decodable` type to decode from response data.
  719. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  720. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  721. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  722. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  723. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  724. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  725. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  726. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  727. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  728. /// by default.
  729. /// - completionHandler: A closure to be executed once the request has finished.
  730. ///
  731. /// - Returns: The request.
  732. @discardableResult
  733. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  734. queue: DispatchQueue = .main,
  735. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  736. decoder: DataDecoder = JSONDecoder(),
  737. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  738. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  739. completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
  740. response(queue: queue,
  741. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  742. decoder: decoder,
  743. emptyResponseCodes: emptyResponseCodes,
  744. emptyRequestMethods: emptyRequestMethods),
  745. completionHandler: completionHandler)
  746. }
  747. }
  748. extension DownloadRequest {
  749. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  750. ///
  751. /// - Parameters:
  752. /// - type: `Decodable` type to decode from response data.
  753. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  754. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  755. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  756. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  757. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  758. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  759. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  760. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  761. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  762. /// by default.
  763. /// - completionHandler: A closure to be executed once the request has finished.
  764. ///
  765. /// - Returns: The request.
  766. @discardableResult
  767. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  768. queue: DispatchQueue = .main,
  769. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  770. decoder: DataDecoder = JSONDecoder(),
  771. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  772. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  773. completionHandler: @escaping (AFDownloadResponse<T>) -> Void) -> Self {
  774. response(queue: queue,
  775. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  776. decoder: decoder,
  777. emptyResponseCodes: emptyResponseCodes,
  778. emptyRequestMethods: emptyRequestMethods),
  779. completionHandler: completionHandler)
  780. }
  781. }
  782. // MARK: - DataStreamRequest
  783. /// A type which can serialize incoming `Data`.
  784. public protocol DataStreamSerializer {
  785. /// Type produced from the serialized `Data`.
  786. associatedtype SerializedObject
  787. /// Serializes incoming `Data` into a `SerializedObject` value.
  788. ///
  789. /// - Parameter data: `Data` to be serialized.
  790. ///
  791. /// - Throws: Any error produced during serialization.
  792. func serialize(_ data: Data) throws -> SerializedObject
  793. }
  794. /// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`.
  795. public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer {
  796. /// `DataDecoder` used to decode incoming `Data`.
  797. public let decoder: DataDecoder
  798. /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`.
  799. public let dataPreprocessor: DataPreprocessor
  800. /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`.
  801. /// - Parameters:
  802. /// - decoder: ` DataDecoder` used to decode incoming `Data`.
  803. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the `decoder`.
  804. public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) {
  805. self.decoder = decoder
  806. self.dataPreprocessor = dataPreprocessor
  807. }
  808. public func serialize(_ data: Data) throws -> T {
  809. let processedData = try dataPreprocessor.preprocess(data)
  810. do {
  811. return try decoder.decode(T.self, from: processedData)
  812. } catch {
  813. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  814. }
  815. }
  816. }
  817. /// `DataStreamSerializer` which performs no serialization on incoming `Data`.
  818. public struct PassthroughStreamSerializer: DataStreamSerializer {
  819. public func serialize(_ data: Data) throws -> Data { data }
  820. }
  821. /// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values.
  822. public struct StringStreamSerializer: DataStreamSerializer {
  823. public func serialize(_ data: Data) throws -> String {
  824. String(decoding: data, as: UTF8.self)
  825. }
  826. }
  827. extension DataStreamRequest {
  828. /// Adds a `StreamHandler` which performs no parsing on incoming `Data`.
  829. ///
  830. /// - Parameters:
  831. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  832. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  833. ///
  834. /// - Returns: The `DataStreamRequest`.
  835. @discardableResult
  836. public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
  837. $streamMutableState.write { state in
  838. let capture = (queue, { data in
  839. self.capturingError {
  840. try stream(.init(event: .stream(.success(data)), token: .init(self)))
  841. }
  842. })
  843. state.streams.append(capture)
  844. }
  845. appendStreamCompletion(on: queue, stream: stream)
  846. return self
  847. }
  848. /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`.
  849. ///
  850. /// - Parameters:
  851. /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`.
  852. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  853. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  854. ///
  855. /// - Returns: The `DataStreamRequest`.
  856. @discardableResult
  857. public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
  858. on queue: DispatchQueue = .main,
  859. stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
  860. let parser = { (data: Data) in
  861. self.serializationQueue.async {
  862. // Start work on serialization queue.
  863. let result = Result { try serializer.serialize(data) }
  864. .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
  865. // End work on serialization queue.
  866. queue.async {
  867. self.eventMonitor?.request(self, didParseStream: result)
  868. if result.isFailure, self.automaticallyCancelOnStreamError {
  869. queue.async { self.cancel() }
  870. }
  871. self.capturingError {
  872. try stream(.init(event: .stream(result), token: .init(self)))
  873. }
  874. }
  875. }
  876. }
  877. $streamMutableState.write { $0.streams.append((queue, parser)) }
  878. appendStreamCompletion(on: queue, stream: stream)
  879. return self
  880. }
  881. /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`.
  882. ///
  883. /// - Parameters:
  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 responseStreamString(on queue: DispatchQueue = .main,
  890. stream: @escaping Handler<String, Never>) -> Self {
  891. let parser = { (data: Data) in
  892. self.serializationQueue.async {
  893. // Start work on serialization queue.
  894. let string = String(decoding: data, as: UTF8.self)
  895. // End work on serialization queue.
  896. queue.async {
  897. self.capturingError {
  898. try stream(.init(event: .stream(.success(string)), token: .init(self)))
  899. }
  900. }
  901. }
  902. }
  903. $streamMutableState.write { $0.streams.append((queue, parser)) }
  904. appendStreamCompletion(on: queue, stream: stream)
  905. return self
  906. }
  907. /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`.
  908. ///
  909. /// - Parameters:
  910. /// - type: `Decodable` type to parse incoming `Data` into.
  911. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  912. /// - decoder: `DataDecoder` used to decode the incoming `Data`.
  913. /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`.
  914. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  915. ///
  916. /// - Returns: The `DataStreamRequest`.
  917. @discardableResult
  918. public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
  919. on queue: DispatchQueue = .main,
  920. using decoder: DataDecoder = JSONDecoder(),
  921. preprocessor: DataPreprocessor = PassthroughPreprocessor(),
  922. stream: @escaping Handler<T, AFError>) -> Self {
  923. responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
  924. stream: stream)
  925. }
  926. }