ResponseSerialization.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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 by this serializer.
  29. associatedtype SerializedObject
  30. // /// The HTTP response codes used to indicate empty responses. Defaults to `[204, 205]`.
  31. // var emptyDataResponseCodes: Set<Int> { get }
  32. //
  33. // /// The HTTP methods used to indicate emptry responses. Defaults to `[.head]`.
  34. // var emptyDataRequestMethods: Set<HTTPMethod> { get }
  35. /// The function used to serialize the response data in response handlers.
  36. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
  37. }
  38. //extension DataResponseSerializerProtocol {
  39. // public var emptyDataResponseCodes: Set<Int> { return [204, 205] }
  40. // public var emptyDataRequestMethods: Set<HTTPMethod> { return [.head] }
  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 by this `DownloadResponseSerializerType`.
  45. associatedtype SerializedObject
  46. // /// The HTTP response codes used to indicate empty responses. Defaults to `[204, 205]`.
  47. // var emptyResponseCodes: Set<Int> { get }
  48. //
  49. // /// The HTTP methods used to indicate emptry responses. Defaults to `[.head]`.
  50. // var emptyRequestMethods: Set<HTTPMethod> { get }
  51. /// The function used to serialize the downloaded data in response handlers.
  52. func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
  53. }
  54. extension DownloadResponseSerializerProtocol {
  55. public var emptyDataResponseCodes: Set<Int> { return [204, 205] }
  56. public var emptyDataRequestMethods: Set<HTTPMethod> { return [.head] }
  57. }
  58. /// A serializer that can handle both data and download responses.
  59. public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { }
  60. //extension ResponseSerializer {
  61. // public var emptyDataResponseCodes: Set<Int> { return [204, 205] }
  62. // public var emptyDataRequestMethods: Set<HTTPMethod> { return [.head] }
  63. //}
  64. /// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
  65. /// the data read from disk into the data response serializer.
  66. public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
  67. public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
  68. guard error == nil else { throw error! }
  69. guard let fileURL = fileURL else {
  70. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  71. }
  72. let data: Data
  73. do {
  74. data = try Data(contentsOf: fileURL)
  75. } catch {
  76. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  77. }
  78. do {
  79. return try serialize(request: request, response: response, data: data, error: error)
  80. } catch {
  81. throw error
  82. }
  83. }
  84. }
  85. // MARK: - AnyResponseSerializer
  86. /// A generic `ResponseSerializer` conforming type.
  87. public final class AnyResponseSerializer<Value>: ResponseSerializer {
  88. /// A closure which can be used to serialize data responses.
  89. public typealias DataSerializer = (_ request: URLRequest?, _ response: HTTPURLResponse?, _ data: Data?, _ error: Error?) throws -> Value
  90. /// A closure which can be used to serialize download reponses.
  91. public typealias DownloadSerializer = (_ request: URLRequest?, _ response: HTTPURLResponse?, _ fileURL: URL?, _ error: Error?) throws -> Value
  92. let dataSerializer: DataSerializer
  93. let downloadSerializer: DownloadSerializer?
  94. /// Initialze the instance with both a `DataSerializer` closure and a `DownloadSerializer` closure.
  95. ///
  96. /// - Parameters:
  97. /// - dataSerializer: A `DataSerializer` closure.
  98. /// - downloadSerializer: A `DownloadSerializer` closure.
  99. public init(dataSerializer: @escaping DataSerializer, downloadSerializer: @escaping DownloadSerializer) {
  100. self.dataSerializer = dataSerializer
  101. self.downloadSerializer = downloadSerializer
  102. }
  103. /// Initialze the instance with a `DataSerializer` closure. Download serialization will fallback to a default
  104. /// implementation.
  105. ///
  106. /// - Parameters:
  107. /// - dataSerializer: A `DataSerializer` closure.
  108. public init(dataSerializer: @escaping DataSerializer) {
  109. self.dataSerializer = dataSerializer
  110. self.downloadSerializer = nil
  111. }
  112. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Value {
  113. return try dataSerializer(request, response, data, error)
  114. }
  115. public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Value {
  116. return try downloadSerializer?(request, response, fileURL, error) ?? { (request, response, fileURL, error) in
  117. guard error == nil else { throw error! }
  118. guard let fileURL = fileURL else {
  119. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  120. }
  121. let data: Data
  122. do {
  123. data = try Data(contentsOf: fileURL)
  124. } catch {
  125. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  126. }
  127. do {
  128. return try serialize(request: request, response: response, data: data, error: error)
  129. } catch {
  130. throw error
  131. }
  132. }(request, response, fileURL, error)
  133. }
  134. }
  135. // MARK: - Timeline
  136. //extension Request {
  137. // var timeline: Timeline {
  138. // let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent()
  139. // let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
  140. // let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
  141. //
  142. // return Timeline(
  143. // requestStartTime: requestStartTime,
  144. // initialResponseTime: initialResponseTime,
  145. // requestCompletedTime: requestCompletedTime,
  146. // serializationCompletedTime: CFAbsoluteTimeGetCurrent()
  147. // )
  148. // }
  149. //}
  150. // MARK: - Default
  151. extension DataRequest {
  152. /// Adds a handler to be called once the request has finished.
  153. ///
  154. /// - Parameters:
  155. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  156. /// the handler is called on `.main`.
  157. /// - completionHandler: The code to be executed once the request has finished.
  158. /// - Returns: The request.
  159. @discardableResult
  160. public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Data?>) -> Void) -> Self {
  161. internalQueue.addOperation {
  162. // TODO: Use internal serialization queue?
  163. let result = Result(value: self.data, error: self.error)
  164. let response = DataResponse(request: self.request,
  165. response: self.response,
  166. data: self.data,
  167. metrics: self.metrics,
  168. result: result)
  169. (queue ?? .main).async { completionHandler(response) }
  170. }
  171. return self
  172. }
  173. /// Adds a handler to be called once the request has finished.
  174. ///
  175. /// - Parameters:
  176. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  177. /// the handler is called on `.main`.
  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. /// - Returns: The request.
  181. @discardableResult
  182. public func response<Serializer: DataResponseSerializerProtocol>(
  183. queue: DispatchQueue? = nil,
  184. responseSerializer: Serializer,
  185. completionHandler: @escaping (DataResponse<Serializer.SerializedObject>) -> Void)
  186. -> Self
  187. {
  188. internalQueue.addOperation {
  189. // TODO: Use internal serialization queue?
  190. let result = Result { try responseSerializer.serialize(request: self.request,
  191. response: self.response,
  192. data: self.data,
  193. error: self.error) }
  194. let response = DataResponse(request: self.request,
  195. response: self.response,
  196. data: self.data,
  197. metrics: self.metrics,
  198. result: result)
  199. (queue ?? .main).async { completionHandler(response) }
  200. }
  201. return self
  202. }
  203. }
  204. extension DownloadRequest {
  205. /// Adds a handler to be called once the request has finished.
  206. ///
  207. /// - Parameters:
  208. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  209. /// the handler is called on `.main`.
  210. /// - completionHandler: The code to be executed once the request has finished.
  211. /// - Returns: The request.
  212. @discardableResult
  213. public func response(
  214. queue: DispatchQueue? = nil,
  215. completionHandler: @escaping (DownloadResponse<URL?>) -> Void)
  216. -> Self
  217. {
  218. internalQueue.addOperation {
  219. let result = Result(value: self.temporaryURL ?? self.destinationURL , error: self.error)
  220. let response = DownloadResponse(request: self.request,
  221. response: self.response,
  222. temporaryURL: self.temporaryURL,
  223. destinationURL: self.destinationURL,
  224. resumeData: self.resumeData,
  225. metrics: self.metrics,
  226. result: result)
  227. (queue ?? .main).async { completionHandler(response) }
  228. }
  229. return self
  230. }
  231. /// Adds a handler to be called once the request has finished.
  232. ///
  233. /// - Parameters:
  234. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  235. /// the handler is called on `.main`.
  236. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  237. /// contained in the destination url.
  238. /// - completionHandler: The code to be executed once the request has finished.
  239. /// - Returns: The request.
  240. @discardableResult
  241. public func response<T: DownloadResponseSerializerProtocol>(
  242. queue: DispatchQueue? = nil,
  243. responseSerializer: T,
  244. completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
  245. -> Self
  246. {
  247. internalQueue.addOperation {
  248. // TODO: Use internal serialization queue?
  249. let result = Result { try responseSerializer.serializeDownload(request: self.request,
  250. response: self.response,
  251. fileURL: self.fileURL,
  252. error: self.error) }
  253. let response = DownloadResponse(request: self.request,
  254. response: self.response,
  255. temporaryURL: self.temporaryURL,
  256. destinationURL: self.destinationURL,
  257. resumeData: self.resumeData,
  258. metrics: self.metrics,
  259. result: result)
  260. (queue ?? .main).async { completionHandler(response) }
  261. }
  262. return self
  263. }
  264. }
  265. // MARK: - Data
  266. extension DataRequest {
  267. /// Adds a handler to be called once the request has finished.
  268. ///
  269. /// - Parameters:
  270. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  271. /// the handler is called on `.main`.
  272. /// - completionHandler: The code to be executed once the request has finished.
  273. /// - Returns: The request.
  274. @discardableResult
  275. public func responseData(
  276. queue: DispatchQueue? = nil,
  277. completionHandler: @escaping (DataResponse<Data>) -> Void)
  278. -> Self
  279. {
  280. return response(queue: queue,
  281. responseSerializer: DataResponseSerializer(),
  282. completionHandler: completionHandler)
  283. }
  284. }
  285. /// A `ResponseSerializer` that performs minimal reponse checking and returns any response data as-is. By default, a
  286. /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for
  287. /// empty responses (`204`, `205`), then an empty `Data` value is returned.
  288. public final class DataResponseSerializer: ResponseSerializer {
  289. public init() { }
  290. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
  291. guard error == nil else { throw error! }
  292. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return Data() }
  293. guard let validData = data else {
  294. throw AFError.responseSerializationFailed(reason: .inputDataNil)
  295. }
  296. return validData
  297. }
  298. }
  299. extension DownloadRequest {
  300. /// Adds a handler to be called once the request has finished.
  301. ///
  302. /// - Parameters:
  303. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  304. /// the handler is called on `.main`.
  305. /// - completionHandler: The code to be executed once the request has finished.
  306. /// - Returns: The request.
  307. @discardableResult
  308. public func responseData(
  309. queue: DispatchQueue? = nil,
  310. completionHandler: @escaping (DownloadResponse<Data>) -> Void)
  311. -> Self
  312. {
  313. return response(
  314. queue: queue,
  315. responseSerializer: DataResponseSerializer(),
  316. completionHandler: completionHandler
  317. )
  318. }
  319. }
  320. // MARK: - String
  321. /// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
  322. /// data is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`),
  323. /// then an empty `String` is returned.
  324. public final class StringResponseSerializer: ResponseSerializer {
  325. let encoding: String.Encoding?
  326. /// Creates an instance with the given `String.Encoding`.
  327. ///
  328. /// - Parameter encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined from
  329. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  330. public init(encoding: String.Encoding? = nil) {
  331. self.encoding = encoding
  332. }
  333. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
  334. guard error == nil else { throw error! }
  335. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return "" }
  336. guard let validData = data else {
  337. throw AFError.responseSerializationFailed(reason: .inputDataNil)
  338. }
  339. var convertedEncoding = encoding
  340. if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
  341. let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName)
  342. let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet)
  343. convertedEncoding = String.Encoding(rawValue: nsStringEncoding)
  344. }
  345. let actualEncoding = convertedEncoding ?? .isoLatin1
  346. guard let string = String(data: validData, encoding: actualEncoding) else {
  347. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  348. }
  349. return string
  350. }
  351. }
  352. extension DataRequest {
  353. /// Adds a handler to be called once the request has finished.
  354. ///
  355. /// - Parameters:
  356. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  357. /// the handler is called on `.main`.
  358. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  359. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  360. /// - completionHandler: A closure to be executed once the request has finished.
  361. /// - Returns: The request.
  362. @discardableResult
  363. public func responseString(queue: DispatchQueue? = nil,
  364. encoding: String.Encoding? = nil,
  365. completionHandler: @escaping (DataResponse<String>) -> Void) -> Self {
  366. return response(queue: queue,
  367. responseSerializer: StringResponseSerializer(encoding: encoding),
  368. completionHandler: completionHandler)
  369. }
  370. }
  371. extension DownloadRequest {
  372. /// Adds a handler to be called once the request has finished.
  373. ///
  374. /// - Parameters:
  375. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  376. /// the handler is called on `.main`.
  377. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  378. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  379. /// - completionHandler: A closure to be executed once the request has finished.
  380. /// - Returns: The request.
  381. @discardableResult
  382. public func responseString(
  383. queue: DispatchQueue? = nil,
  384. encoding: String.Encoding? = nil,
  385. completionHandler: @escaping (DownloadResponse<String>) -> Void)
  386. -> Self
  387. {
  388. return response(
  389. queue: queue,
  390. responseSerializer: StringResponseSerializer(encoding: encoding),
  391. completionHandler: completionHandler
  392. )
  393. }
  394. }
  395. // MARK: - JSON
  396. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  397. /// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses
  398. /// (`204`, `205`), then an `NSNull` value is returned.
  399. public final class JSONResponseSerializer: ResponseSerializer {
  400. let options: JSONSerialization.ReadingOptions
  401. /// Creates an instance with the given `JSONSerilization.ReadingOptions`.
  402. ///
  403. /// - Parameter options: The options to use. Defaults to `.allowFragments`.
  404. public init(options: JSONSerialization.ReadingOptions = .allowFragments) {
  405. self.options = options
  406. }
  407. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  408. guard error == nil else { throw error! }
  409. guard let validData = data, validData.count > 0 else {
  410. if let response = response, emptyDataStatusCodes.contains(response.statusCode) {
  411. return NSNull()
  412. }
  413. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  414. }
  415. do {
  416. return try JSONSerialization.jsonObject(with: validData, options: options)
  417. } catch {
  418. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  419. }
  420. }
  421. }
  422. extension DataRequest {
  423. /// Adds a handler to be called once the request has finished.
  424. ///
  425. /// - Parameters:
  426. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  427. /// the handler is called on `.main`.
  428. /// - options: The JSON serialization reading options. Defaults to `.allowFragments`.
  429. /// - completionHandler: A closure to be executed once the request has finished.
  430. /// - Returns: The request.
  431. @discardableResult
  432. public func responseJSON(queue: DispatchQueue? = nil,
  433. options: JSONSerialization.ReadingOptions = .allowFragments,
  434. completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self {
  435. return response(queue: queue,
  436. responseSerializer: JSONResponseSerializer(options: options),
  437. completionHandler: completionHandler)
  438. }
  439. }
  440. extension DownloadRequest {
  441. /// Adds a handler to be called once the request has finished.
  442. ///
  443. /// - Parameters:
  444. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  445. /// the handler is called on `.main`.
  446. /// - options: The JSON serialization reading options. Defaults to `.allowFragments`.
  447. /// - completionHandler: A closure to be executed once the request has finished.
  448. /// - Returns: The request.
  449. @discardableResult
  450. public func responseJSON(
  451. queue: DispatchQueue? = nil,
  452. options: JSONSerialization.ReadingOptions = .allowFragments,
  453. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  454. -> Self
  455. {
  456. return response(queue: queue,
  457. responseSerializer: JSONResponseSerializer(options: options),
  458. completionHandler: completionHandler)
  459. }
  460. }
  461. // MARK: - Empty
  462. /// A type representing an empty response. Use `Empty.response` to get the instance.
  463. public struct Empty: Decodable {
  464. public static let response = Empty()
  465. }
  466. // MARK: - JSON Decodable
  467. /// A `ResponseSerializer` that decodes the response data as a generic value using a `JSONDecoder`. By default, a
  468. /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for
  469. /// empty responses (`204`, `205`), then the `Empty.response` value is returned.
  470. public final class JSONDecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  471. let decoder: JSONDecoder
  472. /// Creates an instance with the given `JSONDecoder` instance.
  473. ///
  474. /// - Parameter decoder: A decoder. Defaults to a `JSONDecoder` with default settings.
  475. public init(decoder: JSONDecoder = JSONDecoder()) {
  476. self.decoder = decoder
  477. }
  478. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  479. guard error == nil else { throw error! }
  480. guard let validData = data, validData.count > 0 else {
  481. if let response = response, emptyDataStatusCodes.contains(response.statusCode) {
  482. guard let emptyResponse = Empty.response as? T else {
  483. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  484. }
  485. return emptyResponse
  486. }
  487. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  488. }
  489. do {
  490. return try decoder.decode(T.self, from: validData)
  491. } catch {
  492. throw error
  493. }
  494. }
  495. }
  496. extension DataRequest {
  497. /// Adds a handler to be called once the request has finished.
  498. ///
  499. /// - Parameters:
  500. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  501. /// the handler is called on `.main`.
  502. /// - decoder: The decoder to use to decode the response. Defaults to a `JSONDecoder` with default
  503. /// settings.
  504. /// - completionHandler: A closure to be executed once the request has finished.
  505. /// - Returns: The request.
  506. @discardableResult
  507. public func responseJSONDecodable<T: Decodable>(queue: DispatchQueue? = nil,
  508. decoder: JSONDecoder = JSONDecoder(),
  509. completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
  510. return response(queue: queue,
  511. responseSerializer: JSONDecodableResponseSerializer(decoder: decoder),
  512. completionHandler: completionHandler)
  513. }
  514. }
  515. /// A set of HTTP response status code that do not contain response data.
  516. private let emptyDataStatusCodes: Set<Int> = [204, 205]