Response.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. /// - temporaryURL: The temporary destination `URL` of the data returned from the server.
  217. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
  218. /// - resumeData: The resume `Data` generated if the request was cancelled.
  219. /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`.
  220. /// - serializationDuration: The duration taken by serialization.
  221. /// - result: The `Result` of response serialization.
  222. public init(request: URLRequest?,
  223. response: HTTPURLResponse?,
  224. fileURL: URL?,
  225. resumeData: Data?,
  226. metrics: URLSessionTaskMetrics?,
  227. serializationDuration: TimeInterval,
  228. result: Result<Success, Failure>) {
  229. self.request = request
  230. self.response = response
  231. self.fileURL = fileURL
  232. self.resumeData = resumeData
  233. self.metrics = metrics
  234. self.serializationDuration = serializationDuration
  235. self.result = result
  236. }
  237. }
  238. // MARK: -
  239. extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
  240. /// The textual representation used when written to an output stream, which includes whether the result was a
  241. /// success or failure.
  242. public var description: String {
  243. "\(result)"
  244. }
  245. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  246. /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
  247. /// actions, and the response serialization result.
  248. public var debugDescription: String {
  249. guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
  250. let requestDescription = DebugDescription.description(of: urlRequest)
  251. let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None"
  252. let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  253. let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
  254. return """
  255. \(requestDescription)
  256. \(responseDescription)
  257. [File URL]: \(fileURL?.path ?? "None")
  258. [Resume Data]: \(resumeDataDescription)
  259. [Network Duration]: \(networkDuration)
  260. [Serialization Duration]: \(serializationDuration)s
  261. [Result]: \(result)
  262. """
  263. }
  264. }
  265. // MARK: -
  266. extension DownloadResponse {
  267. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  268. /// result value as a parameter.
  269. ///
  270. /// Use the `map` method with a closure that does not throw. For example:
  271. ///
  272. /// let possibleData: DownloadResponse<Data> = ...
  273. /// let possibleInt = possibleData.map { $0.count }
  274. ///
  275. /// - parameter transform: A closure that takes the success value of the instance's result.
  276. ///
  277. /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
  278. /// result is a failure, returns a response wrapping the same failure.
  279. public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure> {
  280. DownloadResponse<NewSuccess, Failure>(request: request,
  281. response: response,
  282. fileURL: fileURL,
  283. resumeData: resumeData,
  284. metrics: metrics,
  285. serializationDuration: serializationDuration,
  286. result: result.map(transform))
  287. }
  288. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  289. /// result value as a parameter.
  290. ///
  291. /// Use the `tryMap` method with a closure that may throw an error. For example:
  292. ///
  293. /// let possibleData: DownloadResponse<Data> = ...
  294. /// let possibleObject = possibleData.tryMap {
  295. /// try JSONSerialization.jsonObject(with: $0)
  296. /// }
  297. ///
  298. /// - parameter transform: A closure that takes the success value of the instance's result.
  299. ///
  300. /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
  301. /// instance's result is a failure, returns the same failure.
  302. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error> {
  303. DownloadResponse<NewSuccess, Error>(request: request,
  304. response: response,
  305. fileURL: fileURL,
  306. resumeData: resumeData,
  307. metrics: metrics,
  308. serializationDuration: serializationDuration,
  309. result: result.tryMap(transform))
  310. }
  311. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  312. ///
  313. /// Use the `mapError` function with a closure that does not throw. For example:
  314. ///
  315. /// let possibleData: DownloadResponse<Data> = ...
  316. /// let withMyError = possibleData.mapError { MyError.error($0) }
  317. ///
  318. /// - Parameter transform: A closure that takes the error of the instance.
  319. ///
  320. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  321. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> {
  322. DownloadResponse<Success, NewFailure>(request: request,
  323. response: response,
  324. fileURL: fileURL,
  325. resumeData: resumeData,
  326. metrics: metrics,
  327. serializationDuration: serializationDuration,
  328. result: result.mapError(transform))
  329. }
  330. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  331. ///
  332. /// Use the `tryMapError` function with a closure that may throw an error. For example:
  333. ///
  334. /// let possibleData: DownloadResponse<Data> = ...
  335. /// let possibleObject = possibleData.tryMapError {
  336. /// try someFailableFunction(taking: $0)
  337. /// }
  338. ///
  339. /// - Parameter transform: A throwing closure that takes the error of the instance.
  340. ///
  341. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  342. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> {
  343. DownloadResponse<Success, Error>(request: request,
  344. response: response,
  345. fileURL: fileURL,
  346. resumeData: resumeData,
  347. metrics: metrics,
  348. serializationDuration: serializationDuration,
  349. result: result.tryMapError(transform))
  350. }
  351. }
  352. private enum DebugDescription {
  353. static func description(of request: URLRequest) -> String {
  354. let requestSummary = "\(request.httpMethod!) \(request)"
  355. let requestHeadersDescription = DebugDescription.description(for: request.headers)
  356. let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers)
  357. return """
  358. [Request]: \(requestSummary)
  359. \(requestHeadersDescription.indentingNewlines())
  360. \(requestBodyDescription.indentingNewlines())
  361. """
  362. }
  363. static func description(of response: HTTPURLResponse) -> String {
  364. """
  365. [Response]:
  366. [Status Code]: \(response.statusCode)
  367. \(DebugDescription.description(for: response.headers).indentingNewlines())
  368. """
  369. }
  370. static func description(for headers: HTTPHeaders) -> String {
  371. guard !headers.isEmpty else { return "[Headers]: None" }
  372. let headerDescription = "\(headers.sorted())".indentingNewlines()
  373. return """
  374. [Headers]:
  375. \(headerDescription)
  376. """
  377. }
  378. static func description(for data: Data?,
  379. headers: HTTPHeaders,
  380. allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"],
  381. maximumLength: Int = 100_000) -> String {
  382. guard let data = data, !data.isEmpty else { return "[Body]: None" }
  383. guard
  384. data.count <= maximumLength,
  385. printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true)
  386. else { return "[Body]: \(data.count) bytes" }
  387. return """
  388. [Body]:
  389. \(String(decoding: data, as: UTF8.self)
  390. .trimmingCharacters(in: .whitespacesAndNewlines)
  391. .indentingNewlines())
  392. """
  393. }
  394. }
  395. extension String {
  396. fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String {
  397. let spaces = String(repeating: " ", count: spaceCount)
  398. return replacingOccurrences(of: "\n", with: "\n\(spaces)")
  399. }
  400. }