ResponseSerialization.swift 32 KB

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