ResponseSerialization.swift 36 KB

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