Response.swift 21 KB

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