ResponseSerialization.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 by this serializer.
  29. associatedtype SerializedObject
  30. /// The function used to serialize the response data in response handlers.
  31. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
  32. }
  33. /// The type to which all download response serializers must conform in order to serialize a response.
  34. public protocol DownloadResponseSerializerProtocol {
  35. /// The type of serialized object to be created by this `DownloadResponseSerializerType`.
  36. associatedtype SerializedObject
  37. /// The function used to serialize the downloaded data in response handlers.
  38. func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
  39. }
  40. /// A serializer that can handle both data and download responses.
  41. public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { }
  42. /// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
  43. /// the data read from disk into the data response serializer.
  44. public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
  45. public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
  46. guard error == nil else { throw error! }
  47. guard let fileURL = fileURL else {
  48. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  49. }
  50. let data: Data
  51. do {
  52. data = try Data(contentsOf: fileURL)
  53. } catch {
  54. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  55. }
  56. do {
  57. return try serialize(request: request, response: response, data: data, error: error)
  58. } catch {
  59. throw error
  60. }
  61. }
  62. }
  63. // MARK: - AnyResponseSerializer
  64. /// A generic `ResponseSerializer` conforming type.
  65. public final class AnyResponseSerializer<Value>: ResponseSerializer {
  66. /// A closure which can be used to serialize data responses.
  67. public typealias DataSerializer = (_ request: URLRequest?, _ response: HTTPURLResponse?, _ data: Data?, _ error: Error?) throws -> Value
  68. /// A closure which can be used to serialize download reponses.
  69. public typealias DownloadSerializer = (_ request: URLRequest?, _ response: HTTPURLResponse?, _ fileURL: URL?, _ error: Error?) throws -> Value
  70. let dataSerializer: DataSerializer
  71. let downloadSerializer: DownloadSerializer?
  72. /// Initialze the instance with both a `DataSerializer` closure and a `DownloadSerializer` closure.
  73. ///
  74. /// - Parameters:
  75. /// - dataSerializer: A `DataSerializer` closure.
  76. /// - downloadSerializer: A `DownloadSerializer` closure.
  77. public init(dataSerializer: @escaping DataSerializer, downloadSerializer: @escaping DownloadSerializer) {
  78. self.dataSerializer = dataSerializer
  79. self.downloadSerializer = downloadSerializer
  80. }
  81. /// Initialze the instance with a `DataSerializer` closure. Download serialization will fallback to a default
  82. /// implementation.
  83. ///
  84. /// - Parameters:
  85. /// - dataSerializer: A `DataSerializer` closure.
  86. public init(dataSerializer: @escaping DataSerializer) {
  87. self.dataSerializer = dataSerializer
  88. self.downloadSerializer = nil
  89. }
  90. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Value {
  91. return try dataSerializer(request, response, data, error)
  92. }
  93. public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Value {
  94. return try downloadSerializer?(request, response, fileURL, error) ?? { (request, response, fileURL, error) in
  95. guard error == nil else { throw error! }
  96. guard let fileURL = fileURL else {
  97. throw AFError.responseSerializationFailed(reason: .inputFileNil)
  98. }
  99. let data: Data
  100. do {
  101. data = try Data(contentsOf: fileURL)
  102. } catch {
  103. throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
  104. }
  105. do {
  106. return try serialize(request: request, response: response, data: data, error: error)
  107. } catch {
  108. throw error
  109. }
  110. }(request, response, fileURL, error)
  111. }
  112. }
  113. // MARK: - Default
  114. extension DataRequest {
  115. /// Adds a handler to be called once the request has finished.
  116. ///
  117. /// - Parameters:
  118. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  119. /// the handler is called on `.main`.
  120. /// - completionHandler: The code to be executed once the request has finished.
  121. /// - Returns: The request.
  122. @discardableResult
  123. public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Data?>) -> Void) -> Self {
  124. internalQueue.addOperation {
  125. self.serializationQueue.async {
  126. let result = Result(value: self.data, error: self.error)
  127. let response = DataResponse(request: self.request,
  128. response: self.response,
  129. data: self.data,
  130. metrics: self.metrics,
  131. serializationDuration: 0,
  132. result: result)
  133. self.eventMonitor?.request(self, didParseResponse: response)
  134. (queue ?? .main).async { completionHandler(response) }
  135. }
  136. }
  137. return self
  138. }
  139. /// Adds a handler to be called once the request has finished.
  140. ///
  141. /// - Parameters:
  142. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  143. /// the handler is called on `.main`.
  144. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  145. /// - completionHandler: The code to be executed once the request has finished.
  146. /// - Returns: The request.
  147. @discardableResult
  148. public func response<Serializer: DataResponseSerializerProtocol>(
  149. queue: DispatchQueue? = nil,
  150. responseSerializer: Serializer,
  151. completionHandler: @escaping (DataResponse<Serializer.SerializedObject>) -> Void)
  152. -> Self
  153. {
  154. internalQueue.addOperation {
  155. self.serializationQueue.async {
  156. let start = CFAbsoluteTimeGetCurrent()
  157. let result = Result { try responseSerializer.serialize(request: self.request,
  158. response: self.response,
  159. data: self.data,
  160. error: self.error) }
  161. let end = CFAbsoluteTimeGetCurrent()
  162. let response = DataResponse(request: self.request,
  163. response: self.response,
  164. data: self.data,
  165. metrics: self.metrics,
  166. serializationDuration: (end - start),
  167. result: result)
  168. self.eventMonitor?.request(self, didParseResponse: response)
  169. (queue ?? .main).async { completionHandler(response) }
  170. }
  171. }
  172. return self
  173. }
  174. }
  175. extension DownloadRequest {
  176. /// Adds a handler to be called once the request has finished.
  177. ///
  178. /// - Parameters:
  179. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  180. /// the handler is called on `.main`.
  181. /// - completionHandler: The code to be executed once the request has finished.
  182. /// - Returns: The request.
  183. @discardableResult
  184. public func response(
  185. queue: DispatchQueue? = nil,
  186. completionHandler: @escaping (DownloadResponse<URL?>) -> Void)
  187. -> Self
  188. {
  189. internalQueue.addOperation {
  190. self.serializationQueue.async {
  191. let result = Result(value: self.fileURL , error: self.error)
  192. let response = DownloadResponse(request: self.request,
  193. response: self.response,
  194. fileURL: self.fileURL,
  195. resumeData: self.resumeData,
  196. metrics: self.metrics,
  197. serializationDuration: 0,
  198. result: result)
  199. (queue ?? .main).async { completionHandler(response) }
  200. }
  201. }
  202. return self
  203. }
  204. /// Adds a handler to be called once the request has finished.
  205. ///
  206. /// - Parameters:
  207. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  208. /// the handler is called on `.main`.
  209. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  210. /// contained in the destination url.
  211. /// - completionHandler: The code to be executed once the request has finished.
  212. /// - Returns: The request.
  213. @discardableResult
  214. public func response<T: DownloadResponseSerializerProtocol>(
  215. queue: DispatchQueue? = nil,
  216. responseSerializer: T,
  217. completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
  218. -> Self
  219. {
  220. internalQueue.addOperation {
  221. self.serializationQueue.async {
  222. let start = CFAbsoluteTimeGetCurrent()
  223. let result = Result { try responseSerializer.serializeDownload(request: self.request,
  224. response: self.response,
  225. fileURL: self.fileURL,
  226. error: self.error) }
  227. let end = CFAbsoluteTimeGetCurrent()
  228. let response = DownloadResponse(request: self.request,
  229. response: self.response,
  230. fileURL: self.fileURL,
  231. resumeData: self.resumeData,
  232. metrics: self.metrics,
  233. serializationDuration: (end - start),
  234. result: result)
  235. (queue ?? .main).async { completionHandler(response) }
  236. }
  237. }
  238. return self
  239. }
  240. }
  241. // MARK: - Data
  242. extension DataRequest {
  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. Defaults to `nil`, which means
  247. /// the handler is called on `.main`.
  248. /// - completionHandler: The code to be executed once the request has finished.
  249. /// - Returns: The request.
  250. @discardableResult
  251. public func responseData(
  252. queue: DispatchQueue? = nil,
  253. completionHandler: @escaping (DataResponse<Data>) -> Void)
  254. -> Self
  255. {
  256. return response(queue: queue,
  257. responseSerializer: DataResponseSerializer(),
  258. completionHandler: completionHandler)
  259. }
  260. }
  261. /// A `ResponseSerializer` that performs minimal reponse checking and returns any response data as-is. By default, a
  262. /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for
  263. /// empty responses (`204`, `205`), then an empty `Data` value is returned.
  264. public final class DataResponseSerializer: ResponseSerializer {
  265. public init() { }
  266. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
  267. guard error == nil else { throw error! }
  268. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return Data() }
  269. guard let validData = data else {
  270. throw AFError.responseSerializationFailed(reason: .inputDataNil)
  271. }
  272. return validData
  273. }
  274. }
  275. extension DownloadRequest {
  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. Defaults to `nil`, which means
  280. /// the handler is called on `.main`.
  281. /// - completionHandler: The code to be executed once the request has finished.
  282. /// - Returns: The request.
  283. @discardableResult
  284. public func responseData(
  285. queue: DispatchQueue? = nil,
  286. completionHandler: @escaping (DownloadResponse<Data>) -> Void)
  287. -> Self
  288. {
  289. return response(
  290. queue: queue,
  291. responseSerializer: DataResponseSerializer(),
  292. completionHandler: completionHandler
  293. )
  294. }
  295. }
  296. // MARK: - String
  297. /// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
  298. /// data is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`),
  299. /// then an empty `String` is returned.
  300. public final class StringResponseSerializer: ResponseSerializer {
  301. let encoding: String.Encoding?
  302. /// Creates an instance with the given `String.Encoding`.
  303. ///
  304. /// - Parameter encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined from
  305. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  306. public init(encoding: String.Encoding? = nil) {
  307. self.encoding = encoding
  308. }
  309. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
  310. guard error == nil else { throw error! }
  311. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return "" }
  312. guard let validData = data else {
  313. throw AFError.responseSerializationFailed(reason: .inputDataNil)
  314. }
  315. var convertedEncoding = encoding
  316. if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
  317. let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName)
  318. let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet)
  319. convertedEncoding = String.Encoding(rawValue: nsStringEncoding)
  320. }
  321. let actualEncoding = convertedEncoding ?? .isoLatin1
  322. guard let string = String(data: validData, encoding: actualEncoding) else {
  323. throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
  324. }
  325. return string
  326. }
  327. }
  328. extension DataRequest {
  329. /// Adds a handler to be called once the request has finished.
  330. ///
  331. /// - Parameters:
  332. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  333. /// the handler is called on `.main`.
  334. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  335. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  336. /// - completionHandler: A closure to be executed once the request has finished.
  337. /// - Returns: The request.
  338. @discardableResult
  339. public func responseString(queue: DispatchQueue? = nil,
  340. encoding: String.Encoding? = nil,
  341. completionHandler: @escaping (DataResponse<String>) -> Void) -> Self {
  342. return response(queue: queue,
  343. responseSerializer: StringResponseSerializer(encoding: encoding),
  344. completionHandler: completionHandler)
  345. }
  346. }
  347. extension DownloadRequest {
  348. /// Adds a handler to be called once the request has finished.
  349. ///
  350. /// - Parameters:
  351. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  352. /// the handler is called on `.main`.
  353. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
  354. /// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  355. /// - completionHandler: A closure to be executed once the request has finished.
  356. /// - Returns: The request.
  357. @discardableResult
  358. public func responseString(
  359. queue: DispatchQueue? = nil,
  360. encoding: String.Encoding? = nil,
  361. completionHandler: @escaping (DownloadResponse<String>) -> Void)
  362. -> Self
  363. {
  364. return response(
  365. queue: queue,
  366. responseSerializer: StringResponseSerializer(encoding: encoding),
  367. completionHandler: completionHandler
  368. )
  369. }
  370. }
  371. // MARK: - JSON
  372. /// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
  373. /// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses
  374. /// (`204`, `205`), then an `NSNull` value is returned.
  375. public final class JSONResponseSerializer: ResponseSerializer {
  376. let options: JSONSerialization.ReadingOptions
  377. /// Creates an instance with the given `JSONSerilization.ReadingOptions`.
  378. ///
  379. /// - Parameter options: The options to use. Defaults to `.allowFragments`.
  380. public init(options: JSONSerialization.ReadingOptions = .allowFragments) {
  381. self.options = options
  382. }
  383. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
  384. guard error == nil else { throw error! }
  385. guard let validData = data, validData.count > 0 else {
  386. if let response = response, emptyDataStatusCodes.contains(response.statusCode) {
  387. return NSNull()
  388. }
  389. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  390. }
  391. do {
  392. return try JSONSerialization.jsonObject(with: validData, options: options)
  393. } catch {
  394. throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
  395. }
  396. }
  397. }
  398. extension DataRequest {
  399. /// Adds a handler to be called once the request has finished.
  400. ///
  401. /// - Parameters:
  402. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  403. /// the handler is called on `.main`.
  404. /// - options: The JSON serialization reading options. Defaults to `.allowFragments`.
  405. /// - completionHandler: A closure to be executed once the request has finished.
  406. /// - Returns: The request.
  407. @discardableResult
  408. public func responseJSON(queue: DispatchQueue? = nil,
  409. options: JSONSerialization.ReadingOptions = .allowFragments,
  410. completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self {
  411. return response(queue: queue,
  412. responseSerializer: JSONResponseSerializer(options: options),
  413. completionHandler: completionHandler)
  414. }
  415. }
  416. extension DownloadRequest {
  417. /// Adds a handler to be called once the request has finished.
  418. ///
  419. /// - Parameters:
  420. /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means
  421. /// the handler is called on `.main`.
  422. /// - options: The JSON serialization reading options. Defaults to `.allowFragments`.
  423. /// - completionHandler: A closure to be executed once the request has finished.
  424. /// - Returns: The request.
  425. @discardableResult
  426. public func responseJSON(
  427. queue: DispatchQueue? = nil,
  428. options: JSONSerialization.ReadingOptions = .allowFragments,
  429. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  430. -> Self
  431. {
  432. return response(queue: queue,
  433. responseSerializer: JSONResponseSerializer(options: options),
  434. completionHandler: completionHandler)
  435. }
  436. }
  437. // MARK: - Empty
  438. /// A type representing an empty response. Use `Empty.response` to get the instance.
  439. public struct Empty: Decodable {
  440. public static let response = Empty()
  441. }
  442. // MARK: - JSON Decodable
  443. /// A `ResponseSerializer` that decodes the response data as a generic value using a `JSONDecoder`. By default, a
  444. /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for
  445. /// empty responses (`204`, `205`), then the `Empty.response` value is returned.
  446. public final class JSONDecodableResponseSerializer<T: Decodable>: ResponseSerializer {
  447. let decoder: JSONDecoder
  448. /// Creates an instance with the given `JSONDecoder` instance.
  449. ///
  450. /// - Parameter decoder: A decoder. Defaults to a `JSONDecoder` with default settings.
  451. public init(decoder: JSONDecoder = JSONDecoder()) {
  452. self.decoder = decoder
  453. }
  454. public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
  455. guard error == nil else { throw error! }
  456. guard let validData = data, validData.count > 0 else {
  457. if let response = response, emptyDataStatusCodes.contains(response.statusCode) {
  458. guard let emptyResponse = Empty.response as? T else {
  459. throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
  460. }
  461. return emptyResponse
  462. }
  463. throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
  464. }
  465. do {
  466. return try decoder.decode(T.self, from: validData)
  467. } catch {
  468. throw error
  469. }
  470. }
  471. }
  472. extension DataRequest {
  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. Defaults to `nil`, which means
  477. /// the handler is called on `.main`.
  478. /// - decoder: The decoder to use to decode the response. Defaults to a `JSONDecoder` with default
  479. /// settings.
  480. /// - completionHandler: A closure to be executed once the request has finished.
  481. /// - Returns: The request.
  482. @discardableResult
  483. public func responseJSONDecodable<T: Decodable>(queue: DispatchQueue? = nil,
  484. decoder: JSONDecoder = JSONDecoder(),
  485. completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
  486. return response(queue: queue,
  487. responseSerializer: JSONDecodableResponseSerializer(decoder: decoder),
  488. completionHandler: completionHandler)
  489. }
  490. }
  491. /// A set of HTTP response status code that do not contain response data.
  492. private let emptyDataStatusCodes: Set<Int> = [204, 205]