ResponseSerialization.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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 { 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. (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 { PassthroughPreprocessor() }
  88. /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default.
  89. public static var defaultEmptyRequestMethods: Set<HTTPMethod> { [.head] }
  90. /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default.
  91. public static var defaultEmptyResponseCodes: Set<Int> { [204, 205] }
  92. public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor }
  93. public var emptyRequestMethods: Set<HTTPMethod> { Self.defaultEmptyRequestMethods }
  94. public var emptyResponseCodes: Set<Int> { 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. 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. 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. (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 = ProcessInfo.processInfo.systemUptime
  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 = ProcessInfo.processInfo.systemUptime
  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 = ProcessInfo.processInfo.systemUptime
  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 = ProcessInfo.processInfo.systemUptime
  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. 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. 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, convertedEncoding == nil {
  444. convertedEncoding = String.Encoding(ianaCharsetName: encodingName)
  445. }
  446. let actualEncoding = convertedEncoding ?? .isoLatin1
  447. guard let string = String(data: data, encoding: actualEncoding) else {
  448. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  449. }
  450. return string
  451. }
  452. }
  453. extension DataRequest {
  454. /// Adds a handler to be called once the request has finished.
  455. ///
  456. /// - Parameters:
  457. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  458. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  459. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  460. /// - completionHandler: A closure to be executed once the request has finished.
  461. ///
  462. /// - Returns: The request.
  463. @discardableResult
  464. public func responseString(queue: DispatchQueue = .main,
  465. encoding: String.Encoding? = nil,
  466. completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
  467. response(queue: queue,
  468. responseSerializer: StringResponseSerializer(encoding: encoding),
  469. completionHandler: completionHandler)
  470. }
  471. }
  472. extension DownloadRequest {
  473. /// Adds a handler to be called once the request has finished.
  474. ///
  475. /// - Parameters:
  476. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  477. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  478. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  479. /// - completionHandler: A closure to be executed once the request has finished.
  480. ///
  481. /// - Returns: The request.
  482. @discardableResult
  483. public func responseString(queue: DispatchQueue = .main,
  484. encoding: String.Encoding? = nil,
  485. completionHandler: @escaping (AFDownloadResponse<String>) -> Void)
  486. -> Self {
  487. response(queue: queue,
  488. responseSerializer: StringResponseSerializer(encoding: encoding),
  489. completionHandler: completionHandler)
  490. }
  491. }
  492. // MARK: - JSON
  493. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  494. /// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses
  495. /// (`204`, `205`), then an `NSNull` value is returned.
  496. public final class JSONResponseSerializer: ResponseSerializer {
  497. public let dataPreprocessor: DataPreprocessor
  498. public let emptyResponseCodes: Set<Int>
  499. public let emptyRequestMethods: Set<HTTPMethod>
  500. /// `JSONSerialization.ReadingOptions` used when serializing a response.
  501. public let options: JSONSerialization.ReadingOptions
  502. /// Creates an instance with the provided values.
  503. ///
  504. /// - Parameters:
  505. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  506. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  507. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  508. /// - options: The options to use. `.allowFragments` by default.
  509. public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  510. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  511. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  512. options: JSONSerialization.ReadingOptions = .allowFragments) {
  513. self.dataPreprocessor = dataPreprocessor
  514. self.emptyResponseCodes = emptyResponseCodes
  515. self.emptyRequestMethods = emptyRequestMethods
  516. self.options = options
  517. }
  518. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  519. guard error == nil else { throw error! }
  520. guard var data = data, !data.isEmpty else {
  521. guard emptyResponseAllowed(forRequest: request, response: response) else {
  522. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  523. }
  524. return NSNull()
  525. }
  526. data = try dataPreprocessor.preprocess(data)
  527. do {
  528. return try JSONSerialization.jsonObject(with: data, options: options)
  529. } catch {
  530. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  531. }
  532. }
  533. }
  534. extension DataRequest {
  535. /// Adds a handler to be called once the request has finished.
  536. ///
  537. /// - Parameters:
  538. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  539. /// - options: The JSON serialization reading options. `.allowFragments` by default.
  540. /// - completionHandler: A closure to be executed once the request has finished.
  541. ///
  542. /// - Returns: The request.
  543. @discardableResult
  544. public func responseJSON(queue: DispatchQueue = .main,
  545. options: JSONSerialization.ReadingOptions = .allowFragments,
  546. completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
  547. response(queue: queue,
  548. responseSerializer: JSONResponseSerializer(options: options),
  549. completionHandler: completionHandler)
  550. }
  551. }
  552. extension DownloadRequest {
  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 (AFDownloadResponse<Any>) -> Void)
  565. -> Self {
  566. response(queue: queue,
  567. responseSerializer: JSONResponseSerializer(options: options),
  568. completionHandler: completionHandler)
  569. }
  570. }
  571. // MARK: - Empty
  572. /// Protocol representing an empty response. Use `T.emptyValue()` to get an instance.
  573. public protocol EmptyResponse {
  574. /// Empty value for the conforming type.
  575. ///
  576. /// - Returns: Value of `Self` to use for empty values.
  577. static func emptyValue() -> Self
  578. }
  579. /// Type representing an empty value. Use `Empty.value` to get the static instance.
  580. public struct Empty: Codable {
  581. /// Static `Empty` instance used for all `Empty` responses.
  582. public static let value = Empty()
  583. }
  584. extension Empty: EmptyResponse {
  585. public static func emptyValue() -> Empty {
  586. value
  587. }
  588. }
  589. // MARK: - DataDecoder Protocol
  590. /// Any type which can decode `Data` into a `Decodable` type.
  591. public protocol DataDecoder {
  592. /// Decode `Data` into the provided type.
  593. ///
  594. /// - Parameters:
  595. /// - type: The `Type` to be decoded.
  596. /// - data: The `Data` to be decoded.
  597. ///
  598. /// - Returns: The decoded value of type `D`.
  599. /// - Throws: Any error that occurs during decode.
  600. func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
  601. }
  602. /// `JSONDecoder` automatically conforms to `DataDecoder`.
  603. extension JSONDecoder: DataDecoder {}
  604. // MARK: - Decodable
  605. /// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
  606. /// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
  607. /// is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), then
  608. /// the `Empty.value` value is returned.
  609. public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  610. public let dataPreprocessor: DataPreprocessor
  611. /// The `DataDecoder` instance used to decode responses.
  612. public let decoder: DataDecoder
  613. public let emptyResponseCodes: Set<Int>
  614. public let emptyRequestMethods: Set<HTTPMethod>
  615. /// Creates an instance using the values provided.
  616. ///
  617. /// - Parameters:
  618. /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
  619. /// - decoder: The `DataDecoder`. `JSONDecoder()` by default.
  620. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  621. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
  622. public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
  623. decoder: DataDecoder = JSONDecoder(),
  624. emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
  625. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
  626. self.dataPreprocessor = dataPreprocessor
  627. self.decoder = decoder
  628. self.emptyResponseCodes = emptyResponseCodes
  629. self.emptyRequestMethods = emptyRequestMethods
  630. }
  631. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  632. guard error == nil else { throw error! }
  633. guard var data = data, !data.isEmpty else {
  634. guard emptyResponseAllowed(forRequest: request, response: response) else {
  635. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  636. }
  637. guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
  638. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  639. }
  640. return emptyValue
  641. }
  642. data = try dataPreprocessor.preprocess(data)
  643. do {
  644. return try decoder.decode(T.self, from: data)
  645. } catch {
  646. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  647. }
  648. }
  649. }
  650. extension DataRequest {
  651. /// Adds a handler to be called once the request has finished.
  652. ///
  653. /// - Parameters:
  654. /// - type: `Decodable` type to decode from response data.
  655. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  656. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  657. /// - completionHandler: A closure to be executed once the request has finished.
  658. ///
  659. /// - Returns: The request.
  660. @discardableResult
  661. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  662. queue: DispatchQueue = .main,
  663. decoder: DataDecoder = JSONDecoder(),
  664. completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
  665. response(queue: queue,
  666. responseSerializer: DecodableResponseSerializer(decoder: decoder),
  667. completionHandler: completionHandler)
  668. }
  669. }
  670. extension DownloadRequest {
  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 (AFDownloadResponse<T>) -> Void) -> Self {
  685. response(queue: queue,
  686. responseSerializer: DecodableResponseSerializer(decoder: decoder),
  687. completionHandler: completionHandler)
  688. }
  689. }
  690. // MARK: - DataStreamRequest
  691. /// A type which can serialize incoming `Data`.
  692. public protocol DataStreamSerializer {
  693. /// Type produced from the serialized `Data`.
  694. associatedtype SerializedObject
  695. /// Serializes incoming `Data` into a `SerializedObject` value.
  696. ///
  697. /// - Parameter data: `Data` to be serialized.
  698. ///
  699. /// - Throws: Any error produced during serialization.
  700. func serialize(_ data: Data) throws -> SerializedObject
  701. }
  702. /// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`.
  703. public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer {
  704. /// `DataDecoder` used to decode incoming `Data`.
  705. public let decoder: DataDecoder
  706. /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`.
  707. public let dataPreprocessor: DataPreprocessor
  708. /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`.
  709. /// - Parameters:
  710. /// - decoder: ` DataDecoder` used to decode incoming `Data`.
  711. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the `decoder`.
  712. public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) {
  713. self.decoder = decoder
  714. self.dataPreprocessor = dataPreprocessor
  715. }
  716. public func serialize(_ data: Data) throws -> T {
  717. let processedData = try dataPreprocessor.preprocess(data)
  718. do {
  719. return try decoder.decode(T.self, from: processedData)
  720. } catch {
  721. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  722. }
  723. }
  724. }
  725. extension DataStreamRequest {
  726. /// Adds a stream handler which performs no parsing on incoming `Data`.
  727. ///
  728. /// - Parameters:
  729. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  730. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  731. ///
  732. /// - Returns: The `DataStreamRequest`.
  733. @discardableResult
  734. public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
  735. $streamMutableState.write { state in
  736. let capture = (queue, { data in
  737. self.capturingError {
  738. try stream(.init(event: .stream(.success(data)), token: .init(self)))
  739. }
  740. })
  741. state.streams.append(capture)
  742. }
  743. appendStreamCompletion(on: queue, stream: stream)
  744. return self
  745. }
  746. /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`.
  747. ///
  748. /// - Parameters:
  749. /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`.
  750. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  751. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  752. ///
  753. /// - Returns: The `DataStreamRequest`.
  754. @discardableResult
  755. public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
  756. on queue: DispatchQueue = .main,
  757. stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
  758. let parser = { (data: Data) in
  759. self.serializationQueue.async {
  760. // Start work on serialization queue.
  761. let result = Result { try serializer.serialize(data) }
  762. .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
  763. // End work on serialization queue.
  764. queue.async {
  765. self.eventMonitor?.request(self, didParseStream: result)
  766. if result.isFailure, self.automaticallyCancelOnStreamError {
  767. queue.async { self.cancel() }
  768. }
  769. self.capturingError {
  770. try stream(.init(event: .stream(result), token: .init(self)))
  771. }
  772. }
  773. }
  774. }
  775. $streamMutableState.write { $0.streams.append((queue, parser)) }
  776. appendStreamCompletion(on: queue, stream: stream)
  777. return self
  778. }
  779. /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`.
  780. ///
  781. /// - Parameters:
  782. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  783. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  784. ///
  785. /// - Returns: The `DataStreamRequest`.
  786. @discardableResult
  787. public func responseStreamString(on queue: DispatchQueue = .main,
  788. stream: @escaping Handler<String, Never>) -> Self {
  789. let parser = { (data: Data) in
  790. self.serializationQueue.async {
  791. // Start work on serialization queue.
  792. let string = String(decoding: data, as: UTF8.self)
  793. // End work on serialization queue.
  794. queue.async {
  795. self.capturingError {
  796. try stream(.init(event: .stream(.success(string)), token: .init(self)))
  797. }
  798. }
  799. }
  800. }
  801. $streamMutableState.write { $0.streams.append((queue, parser)) }
  802. appendStreamCompletion(on: queue, stream: stream)
  803. return self
  804. }
  805. /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`.
  806. ///
  807. /// - Parameters:
  808. /// - type: `Decodable` type to parse incoming `Data` into.
  809. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  810. /// - decoder: `DataDecoder` used to decode the incoming `Data`.
  811. /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`.
  812. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  813. ///
  814. /// - Returns: The `DataStreamRequest`.
  815. @discardableResult
  816. public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
  817. on queue: DispatchQueue = .main,
  818. using decoder: DataDecoder = JSONDecoder(),
  819. preprocessor: DataPreprocessor = PassthroughPreprocessor(),
  820. stream: @escaping Handler<T, AFError>) -> Self {
  821. responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
  822. stream: stream)
  823. }
  824. }