ResponseSerialization.swift 36 KB

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