ResponseSerialization.swift 33 KB

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