ResponseSerialization.swift 57 KB

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