Response.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //
  2. // Response.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. /// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type.
  26. public typealias AFDataResponse<Success> = DataResponse<Success, AFError>
  27. /// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type.
  28. public typealias AFDownloadResponse<Success> = DownloadResponse<Success, AFError>
  29. /// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`.
  30. public struct DataResponse<Success, Failure: Error> {
  31. /// The URL request sent to the server.
  32. public let request: URLRequest?
  33. /// The server's response to the URL request.
  34. public let response: HTTPURLResponse?
  35. /// The data returned by the server.
  36. public let data: Data?
  37. /// The final metrics of the response.
  38. ///
  39. /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
  40. ///
  41. public let metrics: URLSessionTaskMetrics?
  42. /// The time taken to serialize the response.
  43. public let serializationDuration: TimeInterval
  44. /// The result of response serialization.
  45. public let result: Result<Success, Failure>
  46. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  47. public var value: Success? { result.success }
  48. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  49. public var error: Failure? { result.failure }
  50. /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization.
  51. ///
  52. /// - Parameters:
  53. /// - request: The `URLRequest` sent to the server.
  54. /// - response: The `HTTPURLResponse` from the server.
  55. /// - data: The `Data` returned by the server.
  56. /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`.
  57. /// - serializationDuration: The duration taken by serialization.
  58. /// - result: The `Result` of response serialization.
  59. public init(request: URLRequest?,
  60. response: HTTPURLResponse?,
  61. data: Data?,
  62. metrics: URLSessionTaskMetrics?,
  63. serializationDuration: TimeInterval,
  64. result: Result<Success, Failure>) {
  65. self.request = request
  66. self.response = response
  67. self.data = data
  68. self.metrics = metrics
  69. self.serializationDuration = serializationDuration
  70. self.result = result
  71. }
  72. }
  73. // MARK: -
  74. extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
  75. /// The textual representation used when written to an output stream, which includes whether the result was a
  76. /// success or failure.
  77. public var description: String {
  78. "\(result)"
  79. }
  80. /// The debug textual representation used when written to an output stream, which includes (if available) a summary
  81. /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the
  82. /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and
  83. /// the `Result` of serialization.
  84. public var debugDescription: String {
  85. guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
  86. let requestDescription = DebugDescription.description(of: urlRequest)
  87. let responseDescription = response.map { response in
  88. let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers)
  89. return """
  90. \(DebugDescription.description(of: response))
  91. \(responseBodyDescription.indentingNewlines())
  92. """
  93. } ?? "[Response]: None"
  94. let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  95. return """
  96. \(requestDescription)
  97. \(responseDescription)
  98. [Network Duration]: \(networkDuration)
  99. [Serialization Duration]: \(serializationDuration)s
  100. [Result]: \(result)
  101. """
  102. }
  103. }
  104. // MARK: -
  105. extension DataResponse {
  106. /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
  107. /// result value as a parameter.
  108. ///
  109. /// Use the `map` method with a closure that does not throw. For example:
  110. ///
  111. /// let possibleData: DataResponse<Data> = ...
  112. /// let possibleInt = possibleData.map { $0.count }
  113. ///
  114. /// - parameter transform: A closure that takes the success value of the instance's result.
  115. ///
  116. /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
  117. /// result is a failure, returns a response wrapping the same failure.
  118. public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure> {
  119. DataResponse<NewSuccess, Failure>(request: request,
  120. response: response,
  121. data: data,
  122. metrics: metrics,
  123. serializationDuration: serializationDuration,
  124. result: result.map(transform))
  125. }
  126. /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
  127. /// value as a parameter.
  128. ///
  129. /// Use the `tryMap` method with a closure that may throw an error. For example:
  130. ///
  131. /// let possibleData: DataResponse<Data> = ...
  132. /// let possibleObject = possibleData.tryMap {
  133. /// try JSONSerialization.jsonObject(with: $0)
  134. /// }
  135. ///
  136. /// - parameter transform: A closure that takes the success value of the instance's result.
  137. ///
  138. /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
  139. /// result is a failure, returns the same failure.
  140. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error> {
  141. DataResponse<NewSuccess, Error>(request: request,
  142. response: response,
  143. data: data,
  144. metrics: metrics,
  145. serializationDuration: serializationDuration,
  146. result: result.tryMap(transform))
  147. }
  148. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  149. ///
  150. /// Use the `mapError` function with a closure that does not throw. For example:
  151. ///
  152. /// let possibleData: DataResponse<Data> = ...
  153. /// let withMyError = possibleData.mapError { MyError.error($0) }
  154. ///
  155. /// - Parameter transform: A closure that takes the error of the instance.
  156. ///
  157. /// - Returns: A `DataResponse` instance containing the result of the transform.
  158. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> {
  159. DataResponse<Success, NewFailure>(request: request,
  160. response: response,
  161. data: data,
  162. metrics: metrics,
  163. serializationDuration: serializationDuration,
  164. result: result.mapError(transform))
  165. }
  166. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  167. ///
  168. /// Use the `tryMapError` function with a closure that may throw an error. For example:
  169. ///
  170. /// let possibleData: DataResponse<Data> = ...
  171. /// let possibleObject = possibleData.tryMapError {
  172. /// try someFailableFunction(taking: $0)
  173. /// }
  174. ///
  175. /// - Parameter transform: A throwing closure that takes the error of the instance.
  176. ///
  177. /// - Returns: A `DataResponse` instance containing the result of the transform.
  178. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> {
  179. DataResponse<Success, Error>(request: request,
  180. response: response,
  181. data: data,
  182. metrics: metrics,
  183. serializationDuration: serializationDuration,
  184. result: result.tryMapError(transform))
  185. }
  186. }
  187. // MARK: -
  188. /// Used to store all data associated with a serialized response of a download request.
  189. public struct DownloadResponse<Success, Failure: Error> {
  190. /// The URL request sent to the server.
  191. public let request: URLRequest?
  192. /// The server's response to the URL request.
  193. public let response: HTTPURLResponse?
  194. /// The final destination URL of the data returned from the server after it is moved.
  195. public let fileURL: URL?
  196. /// The resume data generated if the request was cancelled.
  197. public let resumeData: Data?
  198. /// The final metrics of the response.
  199. ///
  200. /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
  201. ///
  202. public let metrics: URLSessionTaskMetrics?
  203. /// The time taken to serialize the response.
  204. public let serializationDuration: TimeInterval
  205. /// The result of response serialization.
  206. public let result: Result<Success, Failure>
  207. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  208. public var value: Success? { result.success }
  209. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  210. public var error: Failure? { result.failure }
  211. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  212. ///
  213. /// - Parameters:
  214. /// - request: The `URLRequest` sent to the server.
  215. /// - response: The `HTTPURLResponse` from the server.
  216. /// - fileURL: The final destination URL of the data returned from the server after it is moved.
  217. /// - resumeData: The resume `Data` generated if the request was cancelled.
  218. /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`.
  219. /// - serializationDuration: The duration taken by serialization.
  220. /// - result: The `Result` of response serialization.
  221. public init(request: URLRequest?,
  222. response: HTTPURLResponse?,
  223. fileURL: URL?,
  224. resumeData: Data?,
  225. metrics: URLSessionTaskMetrics?,
  226. serializationDuration: TimeInterval,
  227. result: Result<Success, Failure>) {
  228. self.request = request
  229. self.response = response
  230. self.fileURL = fileURL
  231. self.resumeData = resumeData
  232. self.metrics = metrics
  233. self.serializationDuration = serializationDuration
  234. self.result = result
  235. }
  236. }
  237. // MARK: -
  238. extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
  239. /// The textual representation used when written to an output stream, which includes whether the result was a
  240. /// success or failure.
  241. public var description: String {
  242. "\(result)"
  243. }
  244. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  245. /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
  246. /// actions, and the response serialization result.
  247. public var debugDescription: String {
  248. guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
  249. let requestDescription = DebugDescription.description(of: urlRequest)
  250. let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None"
  251. let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  252. let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
  253. return """
  254. \(requestDescription)
  255. \(responseDescription)
  256. [File URL]: \(fileURL?.path ?? "None")
  257. [Resume Data]: \(resumeDataDescription)
  258. [Network Duration]: \(networkDuration)
  259. [Serialization Duration]: \(serializationDuration)s
  260. [Result]: \(result)
  261. """
  262. }
  263. }
  264. // MARK: -
  265. extension DownloadResponse {
  266. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  267. /// result value as a parameter.
  268. ///
  269. /// Use the `map` method with a closure that does not throw. For example:
  270. ///
  271. /// let possibleData: DownloadResponse<Data> = ...
  272. /// let possibleInt = possibleData.map { $0.count }
  273. ///
  274. /// - parameter transform: A closure that takes the success value of the instance's result.
  275. ///
  276. /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
  277. /// result is a failure, returns a response wrapping the same failure.
  278. public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure> {
  279. DownloadResponse<NewSuccess, Failure>(request: request,
  280. response: response,
  281. fileURL: fileURL,
  282. resumeData: resumeData,
  283. metrics: metrics,
  284. serializationDuration: serializationDuration,
  285. result: result.map(transform))
  286. }
  287. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  288. /// result value as a parameter.
  289. ///
  290. /// Use the `tryMap` method with a closure that may throw an error. For example:
  291. ///
  292. /// let possibleData: DownloadResponse<Data> = ...
  293. /// let possibleObject = possibleData.tryMap {
  294. /// try JSONSerialization.jsonObject(with: $0)
  295. /// }
  296. ///
  297. /// - parameter transform: A closure that takes the success value of the instance's result.
  298. ///
  299. /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
  300. /// instance's result is a failure, returns the same failure.
  301. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error> {
  302. DownloadResponse<NewSuccess, Error>(request: request,
  303. response: response,
  304. fileURL: fileURL,
  305. resumeData: resumeData,
  306. metrics: metrics,
  307. serializationDuration: serializationDuration,
  308. result: result.tryMap(transform))
  309. }
  310. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  311. ///
  312. /// Use the `mapError` function with a closure that does not throw. For example:
  313. ///
  314. /// let possibleData: DownloadResponse<Data> = ...
  315. /// let withMyError = possibleData.mapError { MyError.error($0) }
  316. ///
  317. /// - Parameter transform: A closure that takes the error of the instance.
  318. ///
  319. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  320. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> {
  321. DownloadResponse<Success, NewFailure>(request: request,
  322. response: response,
  323. fileURL: fileURL,
  324. resumeData: resumeData,
  325. metrics: metrics,
  326. serializationDuration: serializationDuration,
  327. result: result.mapError(transform))
  328. }
  329. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  330. ///
  331. /// Use the `tryMapError` function with a closure that may throw an error. For example:
  332. ///
  333. /// let possibleData: DownloadResponse<Data> = ...
  334. /// let possibleObject = possibleData.tryMapError {
  335. /// try someFailableFunction(taking: $0)
  336. /// }
  337. ///
  338. /// - Parameter transform: A throwing closure that takes the error of the instance.
  339. ///
  340. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  341. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> {
  342. DownloadResponse<Success, Error>(request: request,
  343. response: response,
  344. fileURL: fileURL,
  345. resumeData: resumeData,
  346. metrics: metrics,
  347. serializationDuration: serializationDuration,
  348. result: result.tryMapError(transform))
  349. }
  350. }
  351. private enum DebugDescription {
  352. static func description(of request: URLRequest) -> String {
  353. let requestSummary = "\(request.httpMethod!) \(request)"
  354. let requestHeadersDescription = DebugDescription.description(for: request.headers)
  355. let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers)
  356. return """
  357. [Request]: \(requestSummary)
  358. \(requestHeadersDescription.indentingNewlines())
  359. \(requestBodyDescription.indentingNewlines())
  360. """
  361. }
  362. static func description(of response: HTTPURLResponse) -> String {
  363. """
  364. [Response]:
  365. [Status Code]: \(response.statusCode)
  366. \(DebugDescription.description(for: response.headers).indentingNewlines())
  367. """
  368. }
  369. static func description(for headers: HTTPHeaders) -> String {
  370. guard !headers.isEmpty else { return "[Headers]: None" }
  371. let headerDescription = "\(headers.sorted())".indentingNewlines()
  372. return """
  373. [Headers]:
  374. \(headerDescription)
  375. """
  376. }
  377. static func description(for data: Data?,
  378. headers: HTTPHeaders,
  379. allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"],
  380. maximumLength: Int = 100_000) -> String {
  381. guard let data = data, !data.isEmpty else { return "[Body]: None" }
  382. guard
  383. data.count <= maximumLength,
  384. printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true)
  385. else { return "[Body]: \(data.count) bytes" }
  386. return """
  387. [Body]:
  388. \(String(decoding: data, as: UTF8.self)
  389. .trimmingCharacters(in: .whitespacesAndNewlines)
  390. .indentingNewlines())
  391. """
  392. }
  393. }
  394. extension String {
  395. fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String {
  396. let spaces = String(repeating: " ", count: spaceCount)
  397. return replacingOccurrences(of: "\n", with: "\n\(spaces)")
  398. }
  399. }