Response.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. /// Used to store all data associated with a serialized response of a data or upload request.
  26. public struct DataResponse<Value> {
  27. /// The URL request sent to the server.
  28. public let request: URLRequest?
  29. /// The server's response to the URL request.
  30. public let response: HTTPURLResponse?
  31. /// The data returned by the server.
  32. public let data: Data?
  33. /// The result of response serialization.
  34. public let result: Result<Value>
  35. /// The final metrics of the response.
  36. public let metrics: URLSessionTaskMetrics?
  37. /// The time taken to serialize the response.
  38. public let serializationDuration: TimeInterval
  39. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  40. public var value: Value? { return result.value }
  41. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  42. public var error: Error? { return result.error }
  43. /// Creates a `DataResponse` instance with the specified parameters derviced from the response serialization.
  44. ///
  45. /// - Parameters:
  46. /// - request: The `URLRequest` sent to the server.
  47. /// - response: The `HTTPURLResponse` from the server.
  48. /// - data: The `Data` returned by the server.
  49. /// - metrics: The `URLSessionTaskMetrics` of the serialized response.
  50. /// - serializationDuration: The duration taken by serialization.
  51. /// - result: The `Result` of response serialization.
  52. public init(request: URLRequest?,
  53. response: HTTPURLResponse?,
  54. data: Data?,
  55. metrics: URLSessionTaskMetrics?,
  56. serializationDuration: TimeInterval,
  57. result: Result<Value>) {
  58. self.request = request
  59. self.response = response
  60. self.data = data
  61. self.metrics = metrics
  62. self.serializationDuration = serializationDuration
  63. self.result = result
  64. }
  65. }
  66. // MARK: -
  67. extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
  68. /// The textual representation used when written to an output stream, which includes whether the result was a
  69. /// success or failure.
  70. public var description: String {
  71. return result.debugDescription
  72. }
  73. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  74. /// response, the server data, the response serialization result and the timeline.
  75. public var debugDescription: String {
  76. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  77. let responseDescription = response.map { (response) in
  78. let headers = response.allHeaderFields as! HTTPHeaders
  79. let keys = headers.keys.sorted(by: >)
  80. let sortedHeaders = keys.map { "\($0): \(headers[$0]!)" }.joined(separator: "\n")
  81. return """
  82. Status Code: \(response.statusCode)
  83. Headers: \(sortedHeaders)
  84. """
  85. } ?? "nil"
  86. let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  87. return """
  88. [Request]: \(requestDescription)
  89. [Response]: \(responseDescription)
  90. [Data]: \(data?.description ?? "None")
  91. [Network Duration]: \(metricsDescription)
  92. [Serialization Duration]: \(serializationDuration)s
  93. [Result]: \(result.debugDescription)
  94. """
  95. }
  96. }
  97. // MARK: -
  98. extension DataResponse {
  99. /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
  100. /// result value as a parameter.
  101. ///
  102. /// Use the `map` method with a closure that does not throw. For example:
  103. ///
  104. /// let possibleData: DataResponse<Data> = ...
  105. /// let possibleInt = possibleData.map { $0.count }
  106. ///
  107. /// - parameter transform: A closure that takes the success value of the instance's result.
  108. ///
  109. /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
  110. /// result is a failure, returns a response wrapping the same failure.
  111. public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> {
  112. return DataResponse<T>(request: request,
  113. response: self.response,
  114. data: data,
  115. metrics: metrics,
  116. serializationDuration: serializationDuration,
  117. result: result.map(transform))
  118. }
  119. /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
  120. /// value as a parameter.
  121. ///
  122. /// Use the `flatMap` method with a closure that may throw an error. For example:
  123. ///
  124. /// let possibleData: DataResponse<Data> = ...
  125. /// let possibleObject = possibleData.flatMap {
  126. /// try JSONSerialization.jsonObject(with: $0)
  127. /// }
  128. ///
  129. /// - parameter transform: A closure that takes the success value of the instance's result.
  130. ///
  131. /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
  132. /// result is a failure, returns the same failure.
  133. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> {
  134. return DataResponse<T>(request: request,
  135. response: self.response,
  136. data: data,
  137. metrics: metrics,
  138. serializationDuration: serializationDuration,
  139. result: result.flatMap(transform))
  140. }
  141. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  142. ///
  143. /// Use the `mapError` function with a closure that does not throw. For example:
  144. ///
  145. /// let possibleData: DataResponse<Data> = ...
  146. /// let withMyError = possibleData.mapError { MyError.error($0) }
  147. ///
  148. /// - Parameter transform: A closure that takes the error of the instance.
  149. /// - Returns: A `DataResponse` instance containing the result of the transform.
  150. public func mapError<E: Error>(_ transform: (Error) -> E) -> DataResponse {
  151. return DataResponse(request: request,
  152. response: self.response,
  153. data: data,
  154. metrics: metrics,
  155. serializationDuration: serializationDuration,
  156. result: result.mapError(transform))
  157. }
  158. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  159. ///
  160. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  161. ///
  162. /// let possibleData: DataResponse<Data> = ...
  163. /// let possibleObject = possibleData.flatMapError {
  164. /// try someFailableFunction(taking: $0)
  165. /// }
  166. ///
  167. /// - Parameter transform: A throwing closure that takes the error of the instance.
  168. ///
  169. /// - Returns: A `DataResponse` instance containing the result of the transform.
  170. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DataResponse {
  171. return DataResponse(request: request,
  172. response: self.response,
  173. data: data,
  174. metrics: metrics,
  175. serializationDuration: serializationDuration,
  176. result: result.flatMapError(transform))
  177. }
  178. }
  179. // MARK: -
  180. /// Used to store all data associated with a serialized response of a download request.
  181. public struct DownloadResponse<Value> {
  182. /// The URL request sent to the server.
  183. public let request: URLRequest?
  184. /// The server's response to the URL request.
  185. public let response: HTTPURLResponse?
  186. /// The temporary destination URL of the data returned from the server.
  187. public let temporaryURL: URL?
  188. /// The final destination URL of the data returned from the server if it was moved.
  189. public let destinationURL: URL?
  190. /// The resume data generated if the request was cancelled.
  191. public let resumeData: Data?
  192. /// The result of response serialization.
  193. public let result: Result<Value>
  194. /// The final metrics of the response.
  195. public let metrics: URLSessionTaskMetrics?
  196. /// The time taken to serialize the response.
  197. public let serializationDuration: TimeInterval
  198. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  199. public var value: Value? { return result.value }
  200. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  201. public var error: Error? { return result.error }
  202. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  203. ///
  204. /// - Parameters:
  205. /// - request: The `URLRequest` sent to the server.
  206. /// - response: The `HTTPURLResponse` from the server.
  207. /// - temporaryURL: The temporary destinatio `URL` of the data returned from the server.
  208. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
  209. /// - resumeData: The resume `Data` generated if the request was cancelled.
  210. /// - metrics: The `URLSessionTaskMetrics` of the serialized response.
  211. /// - serializationDuration: The duration taken by serialization.
  212. /// - result: The `Result` of response serialization.
  213. public init(
  214. request: URLRequest?,
  215. response: HTTPURLResponse?,
  216. temporaryURL: URL?,
  217. destinationURL: URL?,
  218. resumeData: Data?,
  219. metrics: URLSessionTaskMetrics?,
  220. serializationDuration: TimeInterval,
  221. result: Result<Value>)
  222. {
  223. self.request = request
  224. self.response = response
  225. self.temporaryURL = temporaryURL
  226. self.destinationURL = destinationURL
  227. self.resumeData = resumeData
  228. self.metrics = metrics
  229. self.serializationDuration = serializationDuration
  230. self.result = result
  231. }
  232. }
  233. // MARK: -
  234. extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
  235. /// The textual representation used when written to an output stream, which includes whether the result was a
  236. /// success or failure.
  237. public var description: String {
  238. return result.debugDescription
  239. }
  240. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  241. /// response, the temporary and destination URLs, the resume data, the response serialization result and the
  242. /// timeline.
  243. public var debugDescription: String {
  244. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  245. let responseDescription = response.map { (response) in
  246. let headers = response.allHeaderFields as! HTTPHeaders
  247. let keys = headers.keys.sorted(by: >)
  248. let sortedHeaders = keys.map { "\($0): \(headers[$0]!)" }.joined(separator: "\n")
  249. return """
  250. Status Code: \(response.statusCode)
  251. Headers: \(sortedHeaders)
  252. """
  253. } ?? "nil"
  254. let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  255. let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
  256. return """
  257. [Request]: \(requestDescription)
  258. [Response]: \(responseDescription)
  259. [TemporaryURL]: \(temporaryURL?.path ?? "nil")
  260. [DestinationURL]: \(destinationURL?.path ?? "nil")
  261. [ResumeData]: \(resumeDataDescription)
  262. [Network Duration]: \(metricsDescription)
  263. [Serialization Duration]: \(serializationDuration)s
  264. [Result]: \(result.debugDescription)
  265. """
  266. }
  267. }
  268. // MARK: -
  269. extension DownloadResponse {
  270. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  271. /// result value as a parameter.
  272. ///
  273. /// Use the `map` method with a closure that does not throw. For example:
  274. ///
  275. /// let possibleData: DownloadResponse<Data> = ...
  276. /// let possibleInt = possibleData.map { $0.count }
  277. ///
  278. /// - parameter transform: A closure that takes the success value of the instance's result.
  279. ///
  280. /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
  281. /// result is a failure, returns a response wrapping the same failure.
  282. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> {
  283. return DownloadResponse<T>(
  284. request: request,
  285. response: self.response,
  286. temporaryURL: temporaryURL,
  287. destinationURL: destinationURL,
  288. resumeData: resumeData,
  289. metrics: metrics,
  290. serializationDuration: serializationDuration,
  291. result: result.map(transform)
  292. )
  293. }
  294. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  295. /// result value as a parameter.
  296. ///
  297. /// Use the `flatMap` method with a closure that may throw an error. For example:
  298. ///
  299. /// let possibleData: DownloadResponse<Data> = ...
  300. /// let possibleObject = possibleData.flatMap {
  301. /// try JSONSerialization.jsonObject(with: $0)
  302. /// }
  303. ///
  304. /// - parameter transform: A closure that takes the success value of the instance's result.
  305. ///
  306. /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
  307. /// instance's result is a failure, returns the same failure.
  308. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> {
  309. return DownloadResponse<T>(
  310. request: request,
  311. response: self.response,
  312. temporaryURL: temporaryURL,
  313. destinationURL: destinationURL,
  314. resumeData: resumeData,
  315. metrics: metrics,
  316. serializationDuration: serializationDuration,
  317. result: result.flatMap(transform)
  318. )
  319. }
  320. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  321. ///
  322. /// Use the `mapError` function with a closure that does not throw. For example:
  323. ///
  324. /// let possibleData: DownloadResponse<Data> = ...
  325. /// let withMyError = possibleData.mapError { MyError.error($0) }
  326. ///
  327. /// - Parameter transform: A closure that takes the error of the instance.
  328. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  329. public func mapError<E: Error>(_ transform: (Error) -> E) -> DownloadResponse {
  330. return DownloadResponse(
  331. request: request,
  332. response: self.response,
  333. temporaryURL: temporaryURL,
  334. destinationURL: destinationURL,
  335. resumeData: resumeData,
  336. metrics: metrics,
  337. serializationDuration: serializationDuration,
  338. result: result.mapError(transform)
  339. )
  340. }
  341. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  342. ///
  343. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  344. ///
  345. /// let possibleData: DownloadResponse<Data> = ...
  346. /// let possibleObject = possibleData.flatMapError {
  347. /// try someFailableFunction(taking: $0)
  348. /// }
  349. ///
  350. /// - Parameter transform: A throwing closure that takes the error of the instance.
  351. ///
  352. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  353. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DownloadResponse {
  354. return DownloadResponse(
  355. request: request,
  356. response: self.response,
  357. temporaryURL: temporaryURL,
  358. destinationURL: destinationURL,
  359. resumeData: resumeData,
  360. metrics: metrics,
  361. serializationDuration: serializationDuration,
  362. result: result.flatMapError(transform)
  363. )
  364. }
  365. }