Response.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 final metrics of the response.
  34. public let metrics: URLSessionTaskMetrics?
  35. /// The time taken to serialize the response.
  36. public let serializationDuration: TimeInterval
  37. /// The result of response serialization.
  38. public let result: Result<Value>
  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 duration of the network and serializatino actions, and the response serialization
  75. /// result.
  76. public var debugDescription: String {
  77. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  78. let responseDescription = response.map { (response) in
  79. let sortedHeaders = response.httpHeaders.sorted()
  80. return """
  81. [Status Code]: \(response.statusCode)
  82. [Headers]:
  83. \(sortedHeaders)
  84. """
  85. } ?? "nil"
  86. let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  87. return """
  88. [Request]: \(requestDescription)
  89. [Response]: \n\(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 final destination URL of the data returned from the server after it is moved.
  187. public let fileURL: URL?
  188. /// The resume data generated if the request was cancelled.
  189. public let resumeData: Data?
  190. /// The final metrics of the response.
  191. public let metrics: URLSessionTaskMetrics?
  192. /// The time taken to serialize the response.
  193. public let serializationDuration: TimeInterval
  194. /// The result of response serialization.
  195. public let result: Result<Value>
  196. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  197. public var value: Value? { return result.value }
  198. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  199. public var error: Error? { return result.error }
  200. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  201. ///
  202. /// - Parameters:
  203. /// - request: The `URLRequest` sent to the server.
  204. /// - response: The `HTTPURLResponse` from the server.
  205. /// - temporaryURL: The temporary destinatio `URL` of the data returned from the server.
  206. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
  207. /// - resumeData: The resume `Data` generated if the request was cancelled.
  208. /// - metrics: The `URLSessionTaskMetrics` of the serialized response.
  209. /// - serializationDuration: The duration taken by serialization.
  210. /// - result: The `Result` of response serialization.
  211. public init(
  212. request: URLRequest?,
  213. response: HTTPURLResponse?,
  214. fileURL: URL?,
  215. resumeData: Data?,
  216. metrics: URLSessionTaskMetrics?,
  217. serializationDuration: TimeInterval,
  218. result: Result<Value>)
  219. {
  220. self.request = request
  221. self.response = response
  222. self.fileURL = fileURL
  223. self.resumeData = resumeData
  224. self.metrics = metrics
  225. self.serializationDuration = serializationDuration
  226. self.result = result
  227. }
  228. }
  229. // MARK: -
  230. extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
  231. /// The textual representation used when written to an output stream, which includes whether the result was a
  232. /// success or failure.
  233. public var description: String {
  234. return result.debugDescription
  235. }
  236. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  237. /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
  238. /// actions, and the response serialization result.
  239. public var debugDescription: String {
  240. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  241. let responseDescription = response.map { (response) in
  242. let sortedHeaders = response.httpHeaders.sorted()
  243. return """
  244. [Status Code]: \(response.statusCode)
  245. [Headers]:
  246. \(sortedHeaders)
  247. """
  248. } ?? "nil"
  249. let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  250. let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
  251. return """
  252. [Request]: \(requestDescription)
  253. [Response]: \n\(responseDescription)
  254. [File URL]: \(fileURL?.path ?? "nil")
  255. [ResumeData]: \(resumeDataDescription)
  256. [Network Duration]: \(metricsDescription)
  257. [Serialization Duration]: \(serializationDuration)s
  258. [Result]: \(result.debugDescription)
  259. """
  260. }
  261. }
  262. // MARK: -
  263. extension DownloadResponse {
  264. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  265. /// result value as a parameter.
  266. ///
  267. /// Use the `map` method with a closure that does not throw. For example:
  268. ///
  269. /// let possibleData: DownloadResponse<Data> = ...
  270. /// let possibleInt = possibleData.map { $0.count }
  271. ///
  272. /// - parameter transform: A closure that takes the success value of the instance's result.
  273. ///
  274. /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
  275. /// result is a failure, returns a response wrapping the same failure.
  276. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> {
  277. return DownloadResponse<T>(
  278. request: request,
  279. response: response,
  280. fileURL: fileURL,
  281. resumeData: resumeData,
  282. metrics: metrics,
  283. serializationDuration: serializationDuration,
  284. result: result.map(transform)
  285. )
  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 `flatMap` method with a closure that may throw an error. For example:
  291. ///
  292. /// let possibleData: DownloadResponse<Data> = ...
  293. /// let possibleObject = possibleData.flatMap {
  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 flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> {
  302. return DownloadResponse<T>(
  303. request: request,
  304. response: response,
  305. fileURL: fileURL,
  306. resumeData: resumeData,
  307. metrics: metrics,
  308. serializationDuration: serializationDuration,
  309. result: result.flatMap(transform)
  310. )
  311. }
  312. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  313. ///
  314. /// Use the `mapError` function with a closure that does not throw. For example:
  315. ///
  316. /// let possibleData: DownloadResponse<Data> = ...
  317. /// let withMyError = possibleData.mapError { MyError.error($0) }
  318. ///
  319. /// - Parameter transform: A closure that takes the error of the instance.
  320. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  321. public func mapError<E: Error>(_ transform: (Error) -> E) -> DownloadResponse {
  322. return DownloadResponse(
  323. request: request,
  324. response: response,
  325. fileURL: fileURL,
  326. resumeData: resumeData,
  327. metrics: metrics,
  328. serializationDuration: serializationDuration,
  329. result: result.mapError(transform)
  330. )
  331. }
  332. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  333. ///
  334. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  335. ///
  336. /// let possibleData: DownloadResponse<Data> = ...
  337. /// let possibleObject = possibleData.flatMapError {
  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. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DownloadResponse {
  345. return DownloadResponse(
  346. request: request,
  347. response: response,
  348. fileURL: fileURL,
  349. resumeData: resumeData,
  350. metrics: metrics,
  351. serializationDuration: serializationDuration,
  352. result: result.flatMapError(transform)
  353. )
  354. }
  355. }