ResponseSerialization.swift 37 KB

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