ResponseSerialization.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. /// The type to which all data response serializers must conform in order to serialize a response.
  26. public protocol DataResponseSerializerProtocol<SerializedObject> {
  27. /// The type of serialized object to be created.
  28. associatedtype SerializedObject
  29. /// Serialize the response `Data` into the provided type.
  30. ///
  31. /// - Parameters:
  32. /// - request: `URLRequest` which was used to perform the request, if any.
  33. /// - response: `HTTPURLResponse` received from the server, if any.
  34. /// - data: `Data` returned from the server, if any.
  35. /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
  36. ///
  37. /// - Returns: The `SerializedObject`.
  38. /// - Throws: Any `Error` produced during serialization.
  39. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
  40. }
  41. /// The type to which all download response serializers must conform in order to serialize a response.
  42. public protocol DownloadResponseSerializerProtocol<SerializedObject> {
  43. /// The type of serialized object to be created.
  44. associatedtype SerializedObject
  45. /// Serialize the downloaded response `Data` from disk into the provided type.
  46. ///
  47. /// - Parameters:
  48. /// - request: `URLRequest` which was used to perform the request, if any.
  49. /// - response: `HTTPURLResponse` received from the server, if any.
  50. /// - fileURL: File `URL` to which the response data was downloaded.
  51. /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
  52. ///
  53. /// - Returns: The `SerializedObject`.
  54. /// - Throws: Any `Error` produced during serialization.
  55. func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
  56. }
  57. /// A serializer that can handle both data and download responses.
  58. public protocol ResponseSerializer<SerializedObject>: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
  59. /// `DataPreprocessor` used to prepare incoming `Data` for serialization.
  60. var dataPreprocessor: DataPreprocessor { get }
  61. /// `HTTPMethod`s for which empty response bodies are considered appropriate.
  62. var emptyRequestMethods: Set<HTTPMethod> { get }
  63. /// HTTP response codes for which empty response bodies are considered appropriate.
  64. var emptyResponseCodes: Set<Int> { get }
  65. }
  66. /// Type used to preprocess `Data` before it handled by a serializer.
  67. public protocol DataPreprocessor {
  68. /// Process `Data` before it's handled by a serializer.
  69. /// - Parameter data: The raw `Data` to process.
  70. func preprocess(_ data: Data) throws -> Data
  71. }
  72. /// `DataPreprocessor` that returns passed `Data` without any transform.
  73. public struct PassthroughPreprocessor: DataPreprocessor {
  74. /// Creates an instance.
  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. /// Creates an instance.
  81. public init() {}
  82. public func preprocess(_ data: Data) throws -> Data {
  83. (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data
  84. }
  85. }
  86. extension DataPreprocessor where Self == PassthroughPreprocessor {
  87. /// Provides a `PassthroughPreprocessor` instance.
  88. public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() }
  89. }
  90. extension DataPreprocessor where Self == GoogleXSSIPreprocessor {
  91. /// Provides a `GoogleXSSIPreprocessor` instance.
  92. public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() }
  93. }
  94. extension ResponseSerializer {
  95. /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default.
  96. public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() }
  97. /// Default `HTTPMethod`s for which empty response bodies are always considered appropriate. `[.head]` by default.
  98. public static var defaultEmptyRequestMethods: Set<HTTPMethod> { [.head] }
  99. /// HTTP response codes for which empty response bodies are always considered appropriate. `[204, 205]` by default.
  100. public static var defaultEmptyResponseCodes: Set<Int> { [204, 205] }
  101. public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor }
  102. public var emptyRequestMethods: Set<HTTPMethod> { Self.defaultEmptyRequestMethods }
  103. public var emptyResponseCodes: Set<Int> { Self.defaultEmptyResponseCodes }
  104. /// Determines whether the `request` allows empty response bodies, if `request` exists.
  105. ///
  106. /// - Parameter request: `URLRequest` to evaluate.
  107. ///
  108. /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`.
  109. public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
  110. request.flatMap(\.httpMethod)
  111. .flatMap(HTTPMethod.init)
  112. .map { emptyRequestMethods.contains($0) }
  113. }
  114. /// Determines whether the `response` allows empty response bodies, if `response` exists.
  115. ///
  116. /// - Parameter response: `HTTPURLResponse` to evaluate.
  117. ///
  118. /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`.
  119. public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
  120. response.map(\.statusCode)
  121. .map { emptyResponseCodes.contains($0) }
  122. }
  123. /// Determines whether `request` and `response` allow empty response bodies.
  124. ///
  125. /// - Parameters:
  126. /// - request: `URLRequest` to evaluate.
  127. /// - response: `HTTPURLResponse` to evaluate.
  128. ///
  129. /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise.
  130. public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
  131. (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
  132. }
  133. }
  134. /// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
  135. /// the data read from disk into the data response serializer.
  136. extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
  137. public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
  138. guard error == nil else { throw error! }
  139. guard let fileURL else {
  140. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  141. }
  142. let data: Data
  143. do {
  144. data = try Data(contentsOf: fileURL)
  145. } catch {
  146. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  147. }
  148. do {
  149. return try serialize(request: request, response: response, data: data, error: error)
  150. } catch {
  151. throw error
  152. }
  153. }
  154. }
  155. // MARK: - URL
  156. /// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL`
  157. /// is present.
  158. public struct URLResponseSerializer: DownloadResponseSerializerProtocol {
  159. /// Creates an instance.
  160. public init() {}
  161. public func serializeDownload(request: URLRequest?,
  162. response: HTTPURLResponse?,
  163. fileURL: URL?,
  164. error: Error?) throws -> URL {
  165. guard error == nil else { throw error! }
  166. guard let url = fileURL else {
  167. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  168. }
  169. return url
  170. }
  171. }
  172. extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer {
  173. /// Provides a `URLResponseSerializer` instance.
  174. public static var url: URLResponseSerializer { URLResponseSerializer() }
  175. }
  176. // MARK: - Data
  177. /// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a
  178. /// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the
  179. /// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned.
  180. public final class DataResponseSerializer: ResponseSerializer {
  181. public let dataPreprocessor: DataPreprocessor
  182. public let emptyResponseCodes: Set<Int>
  183. public let emptyRequestMethods: Set<HTTPMethod>
  184. /// Creates a `DataResponseSerializer` using the provided parameters.
  185. ///
  186. /// - Parameters:
  187. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  188. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  189. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  190. public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  191. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  192. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
  193. self.dataPreprocessor = dataPreprocessor
  194. self.emptyResponseCodes = emptyResponseCodes
  195. self.emptyRequestMethods = emptyRequestMethods
  196. }
  197. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
  198. guard error == nil else { throw error! }
  199. guard var data, !data.isEmpty else {
  200. guard emptyResponseAllowed(forRequest: request, response: response) else {
  201. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  202. }
  203. return Data()
  204. }
  205. data = try dataPreprocessor.preprocess(data)
  206. return data
  207. }
  208. }
  209. extension ResponseSerializer where Self == DataResponseSerializer {
  210. /// Provides a default `DataResponseSerializer` instance.
  211. public static var data: DataResponseSerializer { DataResponseSerializer() }
  212. /// Creates a `DataResponseSerializer` using the provided parameters.
  213. ///
  214. /// - Parameters:
  215. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  216. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  217. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  218. ///
  219. /// - Returns: The `DataResponseSerializer`.
  220. public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  221. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  222. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer {
  223. DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  224. emptyResponseCodes: emptyResponseCodes,
  225. emptyRequestMethods: emptyRequestMethods)
  226. }
  227. }
  228. // MARK: - String
  229. /// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
  230. /// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code
  231. /// valid for empty responses, then an empty `String` is returned.
  232. public final class StringResponseSerializer: ResponseSerializer {
  233. public let dataPreprocessor: DataPreprocessor
  234. /// Optional string encoding used to validate the response.
  235. public let encoding: String.Encoding?
  236. public let emptyResponseCodes: Set<Int>
  237. public let emptyRequestMethods: Set<HTTPMethod>
  238. /// Creates an instance with the provided values.
  239. ///
  240. /// - Parameters:
  241. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  242. /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined
  243. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  244. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  245. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  246. public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  247. encoding: String.Encoding? = nil,
  248. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  249. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
  250. self.dataPreprocessor = dataPreprocessor
  251. self.encoding = encoding
  252. self.emptyResponseCodes = emptyResponseCodes
  253. self.emptyRequestMethods = emptyRequestMethods
  254. }
  255. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
  256. guard error == nil else { throw error! }
  257. guard var data, !data.isEmpty else {
  258. guard emptyResponseAllowed(forRequest: request, response: response) else {
  259. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  260. }
  261. return ""
  262. }
  263. data = try dataPreprocessor.preprocess(data)
  264. var convertedEncoding = encoding
  265. if let encodingName = response?.textEncodingName, convertedEncoding == nil {
  266. convertedEncoding = String.Encoding(ianaCharsetName: encodingName)
  267. }
  268. let actualEncoding = convertedEncoding ?? .isoLatin1
  269. guard let string = String(data: data, encoding: actualEncoding) else {
  270. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  271. }
  272. return string
  273. }
  274. }
  275. extension ResponseSerializer where Self == StringResponseSerializer {
  276. /// Provides a default `StringResponseSerializer` instance.
  277. public static var string: StringResponseSerializer { StringResponseSerializer() }
  278. /// Creates a `StringResponseSerializer` with the provided values.
  279. ///
  280. /// - Parameters:
  281. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  282. /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined
  283. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  284. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  285. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  286. ///
  287. /// - Returns: The `StringResponseSerializer`.
  288. public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  289. encoding: String.Encoding? = nil,
  290. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  291. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer {
  292. StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  293. encoding: encoding,
  294. emptyResponseCodes: emptyResponseCodes,
  295. emptyRequestMethods: emptyRequestMethods)
  296. }
  297. }
  298. // MARK: - JSON
  299. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  300. /// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an
  301. /// HTTP status code valid for empty responses, then an `NSNull` value is returned.
  302. ///
  303. /// - Note: This serializer is deprecated and should not be used. Instead, create concrete types conforming to
  304. /// `Decodable` and use a `DecodableResponseSerializer`.
  305. @available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.")
  306. public final class JSONResponseSerializer: ResponseSerializer {
  307. public let dataPreprocessor: DataPreprocessor
  308. public let emptyResponseCodes: Set<Int>
  309. public let emptyRequestMethods: Set<HTTPMethod>
  310. /// `JSONSerialization.ReadingOptions` used when serializing a response.
  311. public let options: JSONSerialization.ReadingOptions
  312. /// Creates an instance with the provided values.
  313. ///
  314. /// - Parameters:
  315. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  316. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  317. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  318. /// - options: The options to use. `.allowFragments` by default.
  319. public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  320. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  321. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  322. options: JSONSerialization.ReadingOptions = .allowFragments) {
  323. self.dataPreprocessor = dataPreprocessor
  324. self.emptyResponseCodes = emptyResponseCodes
  325. self.emptyRequestMethods = emptyRequestMethods
  326. self.options = options
  327. }
  328. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  329. guard error == nil else { throw error! }
  330. guard var data, !data.isEmpty else {
  331. guard emptyResponseAllowed(forRequest: request, response: response) else {
  332. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  333. }
  334. return NSNull()
  335. }
  336. data = try dataPreprocessor.preprocess(data)
  337. do {
  338. return try JSONSerialization.jsonObject(with: data, options: options)
  339. } catch {
  340. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  341. }
  342. }
  343. }
  344. // MARK: - Empty
  345. /// Protocol representing an empty response. Use `T.emptyValue()` to get an instance.
  346. public protocol EmptyResponse {
  347. /// Empty value for the conforming type.
  348. ///
  349. /// - Returns: Value of `Self` to use for empty values.
  350. static func emptyValue() -> Self
  351. }
  352. /// Type representing an empty value. Use `Empty.value` to get the static instance.
  353. public struct Empty: Codable, Sendable {
  354. /// Static `Empty` instance used for all `Empty` responses.
  355. public static let value = Empty()
  356. }
  357. extension Empty: EmptyResponse {
  358. public static func emptyValue() -> Empty {
  359. value
  360. }
  361. }
  362. // MARK: - DataDecoder Protocol
  363. /// Any type which can decode `Data` into a `Decodable` type.
  364. public protocol DataDecoder {
  365. /// Decode `Data` into the provided type.
  366. ///
  367. /// - Parameters:
  368. /// - type: The `Type` to be decoded.
  369. /// - data: The `Data` to be decoded.
  370. ///
  371. /// - Returns: The decoded value of type `D`.
  372. /// - Throws: Any error that occurs during decode.
  373. func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
  374. }
  375. /// `JSONDecoder` automatically conforms to `DataDecoder`.
  376. extension JSONDecoder: DataDecoder {}
  377. /// `PropertyListDecoder` automatically conforms to `DataDecoder`.
  378. extension PropertyListDecoder: DataDecoder {}
  379. // MARK: - Decodable
  380. /// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
  381. /// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
  382. /// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid
  383. /// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the
  384. /// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the
  385. /// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced.
  386. public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  387. public let dataPreprocessor: DataPreprocessor
  388. /// The `DataDecoder` instance used to decode responses.
  389. public let decoder: DataDecoder
  390. public let emptyResponseCodes: Set<Int>
  391. public let emptyRequestMethods: Set<HTTPMethod>
  392. /// Creates an instance using the values provided.
  393. ///
  394. /// - Parameters:
  395. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  396. /// - decoder: The `DataDecoder`. `JSONDecoder()` by default.
  397. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  398. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  399. public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
  400. decoder: DataDecoder = JSONDecoder(),
  401. emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
  402. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
  403. self.dataPreprocessor = dataPreprocessor
  404. self.decoder = decoder
  405. self.emptyResponseCodes = emptyResponseCodes
  406. self.emptyRequestMethods = emptyRequestMethods
  407. }
  408. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  409. guard error == nil else { throw error! }
  410. guard var data, !data.isEmpty else {
  411. guard emptyResponseAllowed(forRequest: request, response: response) else {
  412. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  413. }
  414. guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
  415. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  416. }
  417. return emptyValue
  418. }
  419. data = try dataPreprocessor.preprocess(data)
  420. do {
  421. return try decoder.decode(T.self, from: data)
  422. } catch {
  423. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  424. }
  425. }
  426. }
  427. extension ResponseSerializer {
  428. /// Creates a `DecodableResponseSerializer` using the values provided.
  429. ///
  430. /// - Parameters:
  431. /// - type: `Decodable` type to decode from response data.
  432. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  433. /// - decoder: The `DataDecoder`. `JSONDecoder()` by default.
  434. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  435. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  436. ///
  437. /// - Returns: The `DecodableResponseSerializer`.
  438. public static func decodable<T: Decodable>(of type: T.Type,
  439. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  440. decoder: DataDecoder = JSONDecoder(),
  441. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  442. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DecodableResponseSerializer<T> where Self == DecodableResponseSerializer<T> {
  443. DecodableResponseSerializer<T>(dataPreprocessor: dataPreprocessor,
  444. decoder: decoder,
  445. emptyResponseCodes: emptyResponseCodes,
  446. emptyRequestMethods: emptyRequestMethods)
  447. }
  448. }