ResponseSerialization.swift 34 KB

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