Response.swift 17 KB

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