ResponseSerialization.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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 function used to serialize the response data in response handlers.
  31. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
  32. }
  33. /// The type to which all download response serializers must conform in order to serialize a response.
  34. public protocol DownloadResponseSerializerProtocol {
  35. /// The type of serialized object to be created by this `DownloadResponseSerializerType`.
  36. associatedtype SerializedObject
  37. /// The function used to serialize the downloaded data in response handlers.
  38. func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
  39. }
  40. /// A serializer that can handle both data and download responses.
  41. public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
  42. var emptyRequestMethods: Set<HTTPMethod> { get }
  43. var emptyResponseCodes: Set<Int> { get }
  44. }
  45. extension ResponseSerializer {
  46. public static var defaultEmptyRequestMethods: Set<HTTPMethod> { return [.head] }
  47. public static var defaultEmptyResponseCodes: Set<Int> { return [204, 205] }
  48. public var emptyRequestMethods: Set<HTTPMethod> { return Self.defaultEmptyRequestMethods }
  49. public var emptyResponseCodes: Set<Int> { return Self.defaultEmptyResponseCodes }
  50. public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
  51. return request.flatMap { $0.httpMethod }
  52. .flatMap(HTTPMethod.init)
  53. .map { emptyRequestMethods.contains($0) }
  54. }
  55. public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
  56. return response.flatMap { $0.statusCode }
  57. .map { emptyResponseCodes.contains($0) }
  58. }
  59. public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
  60. return (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
  61. }
  62. }
  63. /// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
  64. /// the data read from disk into the data response serializer.
  65. public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
  66. func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
  67. guard error == nil else { throw error! }
  68. guard let fileURL = fileURL else {
  69. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  70. }
  71. let data: Data
  72. do {
  73. data = try Data(contentsOf: fileURL)
  74. } catch {
  75. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  76. }
  77. do {
  78. return try serialize(request: request, response: response, data: data, error: error)
  79. } catch {
  80. throw error
  81. }
  82. }
  83. }
  84. // MARK: - Default
  85. extension DataRequest {
  86. /// Adds a handler to be called once the request has finished.
  87. ///
  88. /// - Parameters:
  89. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  90. /// - completionHandler: The code to be executed once the request has finished.
  91. /// - Returns: The request.
  92. @discardableResult
  93. public func response(queue: DispatchQueue = .main, completionHandler: @escaping (DataResponse<Data?>) -> Void) -> Self {
  94. appendResponseSerializer {
  95. let result = AFResult(value: self.data, error: self.error)
  96. let response = DataResponse(request: self.request,
  97. response: self.response,
  98. data: self.data,
  99. metrics: self.metrics,
  100. serializationDuration: 0,
  101. result: result)
  102. self.eventMonitor?.request(self, didParseResponse: response)
  103. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  104. }
  105. return self
  106. }
  107. /// Adds a handler to be called once the request has finished.
  108. ///
  109. /// - Parameters:
  110. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  111. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  112. /// - completionHandler: The code to be executed once the request has finished.
  113. /// - Returns: The request.
  114. @discardableResult
  115. public func response<Serializer: DataResponseSerializerProtocol>(
  116. queue: DispatchQueue = .main,
  117. responseSerializer: Serializer,
  118. completionHandler: @escaping (DataResponse<Serializer.SerializedObject>) -> Void)
  119. -> Self
  120. {
  121. appendResponseSerializer {
  122. let start = CFAbsoluteTimeGetCurrent()
  123. let result = AFResult { try responseSerializer.serialize(request: self.request,
  124. response: self.response,
  125. data: self.data,
  126. error: self.error) }
  127. let end = CFAbsoluteTimeGetCurrent()
  128. let response = DataResponse(request: self.request,
  129. response: self.response,
  130. data: self.data,
  131. metrics: self.metrics,
  132. serializationDuration: (end - start),
  133. result: result)
  134. self.eventMonitor?.request(self, didParseResponse: response)
  135. guard let serializerError = result.error, let delegate = self.delegate else {
  136. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  137. return
  138. }
  139. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  140. var didComplete: (() -> Void)?
  141. defer {
  142. if let didComplete = didComplete {
  143. self.responseSerializerDidComplete { queue.async { didComplete() } }
  144. }
  145. }
  146. switch retryResult {
  147. case .doNotRetry:
  148. didComplete = { completionHandler(response) }
  149. case .doNotRetryWithError(let retryError):
  150. let result = AFResult<Serializer.SerializedObject>.failure(retryError)
  151. let response = DataResponse(request: self.request,
  152. response: self.response,
  153. data: self.data,
  154. metrics: self.metrics,
  155. serializationDuration: (end - start),
  156. result: result)
  157. didComplete = { completionHandler(response) }
  158. case .retry, .retryWithDelay:
  159. delegate.retryRequest(self, withDelay: retryResult.delay)
  160. }
  161. }
  162. }
  163. return self
  164. }
  165. }
  166. extension DownloadRequest {
  167. /// Adds a handler to be called once the request has finished.
  168. ///
  169. /// - Parameters:
  170. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  171. /// - completionHandler: The code to be executed once the request has finished.
  172. /// - Returns: The request.
  173. @discardableResult
  174. public func response(
  175. queue: DispatchQueue = .main,
  176. completionHandler: @escaping (DownloadResponse<URL?>) -> Void)
  177. -> Self
  178. {
  179. appendResponseSerializer {
  180. let result = AFResult(value: self.fileURL , error: self.error)
  181. let response = DownloadResponse(request: self.request,
  182. response: self.response,
  183. fileURL: self.fileURL,
  184. resumeData: self.resumeData,
  185. metrics: self.metrics,
  186. serializationDuration: 0,
  187. result: result)
  188. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  189. }
  190. return self
  191. }
  192. /// Adds a handler to be called once the request has finished.
  193. ///
  194. /// - Parameters:
  195. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  196. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  197. /// contained in the destination url.
  198. /// - completionHandler: The code to be executed once the request has finished.
  199. /// - Returns: The request.
  200. @discardableResult
  201. public func response<T: DownloadResponseSerializerProtocol>(
  202. queue: DispatchQueue = .main,
  203. responseSerializer: T,
  204. completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
  205. -> Self
  206. {
  207. appendResponseSerializer {
  208. let start = CFAbsoluteTimeGetCurrent()
  209. let result = AFResult { try responseSerializer.serializeDownload(request: self.request,
  210. response: self.response,
  211. fileURL: self.fileURL,
  212. error: self.error) }
  213. let end = CFAbsoluteTimeGetCurrent()
  214. let response = DownloadResponse(request: self.request,
  215. response: self.response,
  216. fileURL: self.fileURL,
  217. resumeData: self.resumeData,
  218. metrics: self.metrics,
  219. serializationDuration: (end - start),
  220. result: result)
  221. guard let serializerError = result.error, let delegate = self.delegate else {
  222. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  223. return
  224. }
  225. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  226. var didComplete: (() -> Void)?
  227. defer {
  228. if let didComplete = didComplete {
  229. self.responseSerializerDidComplete { queue.async { didComplete() } }
  230. }
  231. }
  232. switch retryResult {
  233. case .doNotRetry:
  234. didComplete = { completionHandler(response) }
  235. case .doNotRetryWithError(let retryError):
  236. let result = AFResult<T.SerializedObject>.failure(retryError)
  237. let response = DownloadResponse(request: self.request,
  238. response: self.response,
  239. fileURL: self.fileURL,
  240. resumeData: self.resumeData,
  241. metrics: self.metrics,
  242. serializationDuration: (end - start),
  243. result: result)
  244. didComplete = { completionHandler(response) }
  245. case .retry, .retryWithDelay:
  246. delegate.retryRequest(self, withDelay: retryResult.delay)
  247. }
  248. }
  249. }
  250. return self
  251. }
  252. }
  253. // MARK: - Data
  254. extension DataRequest {
  255. /// Adds a handler to be called once the request has finished.
  256. ///
  257. /// - Parameters:
  258. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  259. /// - completionHandler: The code to be executed once the request has finished.
  260. /// - Returns: The request.
  261. @discardableResult
  262. public func responseData(
  263. queue: DispatchQueue = .main,
  264. completionHandler: @escaping (DataResponse<Data>) -> Void)
  265. -> Self
  266. {
  267. return response(queue: queue,
  268. responseSerializer: DataResponseSerializer(),
  269. completionHandler: completionHandler)
  270. }
  271. }
  272. /// A `ResponseSerializer` that performs minimal reponse checking and returns any response data as-is. By default, a
  273. /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for
  274. /// empty responses (`204`, `205`), then an empty `Data` value is returned.
  275. public final class DataResponseSerializer: ResponseSerializer {
  276. /// HTTP response codes for which empty responses are allowed.
  277. public let emptyResponseCodes: Set<Int>
  278. /// HTTP request methods for which empty responses are allowed.
  279. public let emptyRequestMethods: Set<HTTPMethod>
  280. /// Creates an instance using the provided values.
  281. ///
  282. /// - Parameters:
  283. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to
  284. /// `[204, 205]`.
  285. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. Defaults to `[.head]`.
  286. public init(emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  287. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
  288. self.emptyResponseCodes = emptyResponseCodes
  289. self.emptyRequestMethods = emptyRequestMethods
  290. }
  291. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
  292. guard error == nil else { throw error! }
  293. guard let data = data, !data.isEmpty else {
  294. guard emptyResponseAllowed(forRequest: request, response: response) else {
  295. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  296. }
  297. return Data()
  298. }
  299. return data
  300. }
  301. }
  302. extension DownloadRequest {
  303. /// Adds a handler to be called once the request has finished.
  304. ///
  305. /// - Parameters:
  306. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  307. /// - completionHandler: The code to be executed once the request has finished.
  308. /// - Returns: The request.
  309. @discardableResult
  310. public func responseData(
  311. queue: DispatchQueue = .main,
  312. completionHandler: @escaping (DownloadResponse<Data>) -> Void)
  313. -> Self
  314. {
  315. return response(
  316. queue: queue,
  317. responseSerializer: DataResponseSerializer(),
  318. completionHandler: completionHandler
  319. )
  320. }
  321. }
  322. // MARK: - String
  323. /// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
  324. /// data is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`),
  325. /// then an empty `String` is returned.
  326. public final class StringResponseSerializer: ResponseSerializer {
  327. /// Optional string encoding used to validate the response.
  328. public let encoding: String.Encoding?
  329. /// HTTP response codes for which empty responses are allowed.
  330. public let emptyResponseCodes: Set<Int>
  331. /// HTTP request methods for which empty responses are allowed.
  332. public let emptyRequestMethods: Set<HTTPMethod>
  333. /// Creates an instance with the provided values.
  334. ///
  335. /// - Parameters:
  336. /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined
  337. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  338. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to
  339. /// `[204, 205]`.
  340. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. Defaults to `[.head]`.
  341. public init(encoding: String.Encoding? = nil,
  342. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  343. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
  344. self.encoding = encoding
  345. self.emptyResponseCodes = emptyResponseCodes
  346. self.emptyRequestMethods = emptyRequestMethods
  347. }
  348. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
  349. guard error == nil else { throw error! }
  350. guard let data = data, !data.isEmpty else {
  351. guard emptyResponseAllowed(forRequest: request, response: response) else {
  352. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  353. }
  354. return ""
  355. }
  356. var convertedEncoding = encoding
  357. if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
  358. let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName)
  359. let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet)
  360. convertedEncoding = String.Encoding(rawValue: nsStringEncoding)
  361. }
  362. let actualEncoding = convertedEncoding ?? .isoLatin1
  363. guard let string = String(data: data, encoding: actualEncoding) else {
  364. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  365. }
  366. return string
  367. }
  368. }
  369. extension DataRequest {
  370. /// Adds a handler to be called once the request has finished.
  371. ///
  372. /// - Parameters:
  373. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  374. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  375. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  376. /// - completionHandler: A closure to be executed once the request has finished.
  377. /// - Returns: The request.
  378. @discardableResult
  379. public func responseString(queue: DispatchQueue = .main,
  380. encoding: String.Encoding? = nil,
  381. completionHandler: @escaping (DataResponse<String>) -> Void) -> Self {
  382. return response(queue: queue,
  383. responseSerializer: StringResponseSerializer(encoding: encoding),
  384. completionHandler: completionHandler)
  385. }
  386. }
  387. extension DownloadRequest {
  388. /// Adds a handler to be called once the request has finished.
  389. ///
  390. /// - Parameters:
  391. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  392. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  393. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  394. /// - completionHandler: A closure to be executed once the request has finished.
  395. /// - Returns: The request.
  396. @discardableResult
  397. public func responseString(
  398. queue: DispatchQueue = .main,
  399. encoding: String.Encoding? = nil,
  400. completionHandler: @escaping (DownloadResponse<String>) -> Void)
  401. -> Self
  402. {
  403. return response(
  404. queue: queue,
  405. responseSerializer: StringResponseSerializer(encoding: encoding),
  406. completionHandler: completionHandler
  407. )
  408. }
  409. }
  410. // MARK: - JSON
  411. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  412. /// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses
  413. /// (`204`, `205`), then an `NSNull` value is returned.
  414. public final class JSONResponseSerializer: ResponseSerializer {
  415. /// `JSONSerialization.ReadingOptions` used when serializing a response.
  416. public let options: JSONSerialization.ReadingOptions
  417. /// HTTP response codes for which empty responses are allowed.
  418. public let emptyResponseCodes: Set<Int>
  419. /// HTTP request methods for which empty responses are allowed.
  420. public let emptyRequestMethods: Set<HTTPMethod>
  421. /// Creates an instance with the provided values.
  422. ///
  423. /// - Parameters:
  424. /// - options: The options to use. Defaults to `.allowFragments`.
  425. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to
  426. /// `[204, 205]`.
  427. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. Defaults to `[.head]`.
  428. public init(options: JSONSerialization.ReadingOptions = .allowFragments,
  429. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  430. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods) {
  431. self.options = options
  432. self.emptyResponseCodes = emptyResponseCodes
  433. self.emptyRequestMethods = emptyRequestMethods
  434. }
  435. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  436. guard error == nil else { throw error! }
  437. guard let data = data, !data.isEmpty else {
  438. guard emptyResponseAllowed(forRequest: request, response: response) else {
  439. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  440. }
  441. return NSNull()
  442. }
  443. do {
  444. return try JSONSerialization.jsonObject(with: data, options: options)
  445. } catch {
  446. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  447. }
  448. }
  449. }
  450. extension DataRequest {
  451. /// Adds a handler to be called once the request has finished.
  452. ///
  453. /// - Parameters:
  454. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  455. /// - options: The JSON serialization reading options. Defaults to `.allowFragments`.
  456. /// - completionHandler: A closure to be executed once the request has finished.
  457. /// - Returns: The request.
  458. @discardableResult
  459. public func responseJSON(queue: DispatchQueue = .main,
  460. options: JSONSerialization.ReadingOptions = .allowFragments,
  461. completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self {
  462. return response(queue: queue,
  463. responseSerializer: JSONResponseSerializer(options: options),
  464. completionHandler: completionHandler)
  465. }
  466. }
  467. extension DownloadRequest {
  468. /// Adds a handler to be called once the request has finished.
  469. ///
  470. /// - Parameters:
  471. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  472. /// - options: The JSON serialization reading options. Defaults to `.allowFragments`.
  473. /// - completionHandler: A closure to be executed once the request has finished.
  474. /// - Returns: The request.
  475. @discardableResult
  476. public func responseJSON(
  477. queue: DispatchQueue = .main,
  478. options: JSONSerialization.ReadingOptions = .allowFragments,
  479. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  480. -> Self
  481. {
  482. return response(queue: queue,
  483. responseSerializer: JSONResponseSerializer(options: options),
  484. completionHandler: completionHandler)
  485. }
  486. }
  487. // MARK: - Empty
  488. /// A protocol for a type representing an empty response. Use `T.emptyValue` to get an instance.
  489. public protocol EmptyResponse {
  490. static func emptyValue() -> Self
  491. }
  492. /// A type representing an empty response. Use `Empty.value` to get the instance.
  493. public struct Empty: Decodable {
  494. public static let value = Empty()
  495. }
  496. extension Empty: EmptyResponse {
  497. public static func emptyValue() -> Empty {
  498. return value
  499. }
  500. }
  501. // MARK: - DataDecoder Protocol
  502. /// Any type which can decode `Data`.
  503. public protocol DataDecoder {
  504. /// Decode `Data` into the provided type.
  505. ///
  506. /// - Parameters:
  507. /// - type: The `Type` to be decoded.
  508. /// - data: The `Data`
  509. /// - Returns: The decoded value of type `D`.
  510. /// - Throws: Any error that occurs during decode.
  511. func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
  512. }
  513. /// `JSONDecoder` automatically conforms to `DataDecoder`.
  514. extension JSONDecoder: DataDecoder { }
  515. // MARK: - Decodable
  516. /// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
  517. /// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
  518. /// is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), then
  519. /// the `Empty.value` value is returned.
  520. public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  521. /// The `JSONDecoder` instance used to decode responses.
  522. public let decoder: DataDecoder
  523. /// HTTP response codes for which empty responses are allowed.
  524. public let emptyResponseCodes: Set<Int>
  525. /// HTTP request methods for which empty responses are allowed.
  526. public let emptyRequestMethods: Set<HTTPMethod>
  527. /// Creates an instance using the values provided.
  528. ///
  529. /// - Parameters:
  530. /// - decoder: The `JSONDecoder`. Defaults to a `JSONDecoder()`.
  531. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to
  532. /// `[204, 205]`.
  533. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. Defaults to `[.head]`.
  534. public init(decoder: DataDecoder = JSONDecoder(),
  535. emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
  536. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
  537. self.decoder = decoder
  538. self.emptyResponseCodes = emptyResponseCodes
  539. self.emptyRequestMethods = emptyRequestMethods
  540. }
  541. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  542. guard error == nil else { throw error! }
  543. guard let data = data, !data.isEmpty else {
  544. guard emptyResponseAllowed(forRequest: request, response: response) else {
  545. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  546. }
  547. guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
  548. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  549. }
  550. return emptyValue
  551. }
  552. do {
  553. return try decoder.decode(T.self, from: data)
  554. } catch {
  555. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  556. }
  557. }
  558. }
  559. extension DataRequest {
  560. /// Adds a handler to be called once the request has finished.
  561. ///
  562. /// - Parameters:
  563. /// - queue: The queue on which the completion handler is dispatched. Defaults to `.main`.
  564. /// - decoder: The `DataDecoder` to use to decode the response. Defaults to a `JSONDecoder` with default
  565. /// settings.
  566. /// - completionHandler: A closure to be executed once the request has finished.
  567. /// - Returns: The request.
  568. @discardableResult
  569. public func responseDecodable<T: Decodable>(queue: DispatchQueue = .main,
  570. decoder: DataDecoder = JSONDecoder(),
  571. completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
  572. return response(queue: queue,
  573. responseSerializer: DecodableResponseSerializer(decoder: decoder),
  574. completionHandler: completionHandler)
  575. }
  576. }