Response.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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: AFResult<Value>
  39. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  40. public var value: Value? { return result.success }
  41. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  42. public var error: Error? { 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 `AFResult` of response serialization.
  52. public init(request: URLRequest?,
  53. response: HTTPURLResponse?,
  54. data: Data?,
  55. metrics: URLSessionTaskMetrics?,
  56. serializationDuration: TimeInterval,
  57. result: AFResult<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)"
  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<T>(_ transform: (Value) -> T) -> DataResponse<T> {
  116. return DataResponse<T>(request: request,
  117. response: self.response,
  118. data: data,
  119. metrics: metrics,
  120. serializationDuration: serializationDuration,
  121. result: result.map(transform))
  122. }
  123. /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
  124. /// value as a parameter.
  125. ///
  126. /// Use the `flatMap` method with a closure that may throw an error. For example:
  127. ///
  128. /// let possibleData: DataResponse<Data> = ...
  129. /// let possibleObject = possibleData.flatMap {
  130. /// try JSONSerialization.jsonObject(with: $0)
  131. /// }
  132. ///
  133. /// - parameter transform: A closure that takes the success value of the instance's result.
  134. ///
  135. /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
  136. /// result is a failure, returns the same failure.
  137. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> {
  138. return DataResponse<T>(request: request,
  139. response: self.response,
  140. data: data,
  141. metrics: metrics,
  142. serializationDuration: serializationDuration,
  143. result: result.flatMap(transform))
  144. }
  145. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  146. ///
  147. /// Use the `mapError` function with a closure that does not throw. For example:
  148. ///
  149. /// let possibleData: DataResponse<Data> = ...
  150. /// let withMyError = possibleData.mapError { MyError.error($0) }
  151. ///
  152. /// - Parameter transform: A closure that takes the error of the instance.
  153. ///
  154. /// - Returns: A `DataResponse` instance containing the result of the transform.
  155. public func mapError<E: Error>(_ transform: (Error) -> E) -> DataResponse {
  156. return DataResponse(request: request,
  157. response: self.response,
  158. data: data,
  159. metrics: metrics,
  160. serializationDuration: serializationDuration,
  161. result: result.mapError(transform))
  162. }
  163. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  164. ///
  165. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  166. ///
  167. /// let possibleData: DataResponse<Data> = ...
  168. /// let possibleObject = possibleData.flatMapError {
  169. /// try someFailableFunction(taking: $0)
  170. /// }
  171. ///
  172. /// - Parameter transform: A throwing closure that takes the error of the instance.
  173. ///
  174. /// - Returns: A `DataResponse` instance containing the result of the transform.
  175. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DataResponse {
  176. return DataResponse(request: request,
  177. response: self.response,
  178. data: data,
  179. metrics: metrics,
  180. serializationDuration: serializationDuration,
  181. result: result.flatMapError(transform))
  182. }
  183. }
  184. // MARK: -
  185. /// Used to store all data associated with a serialized response of a download request.
  186. public struct DownloadResponse<Value> {
  187. /// The URL request sent to the server.
  188. public let request: URLRequest?
  189. /// The server's response to the URL request.
  190. public let response: HTTPURLResponse?
  191. /// The final destination URL of the data returned from the server after it is moved.
  192. public let fileURL: URL?
  193. /// The resume data generated if the request was cancelled.
  194. public let resumeData: Data?
  195. /// The final metrics of the response.
  196. public let metrics: URLSessionTaskMetrics?
  197. /// The time taken to serialize the response.
  198. public let serializationDuration: TimeInterval
  199. /// The result of response serialization.
  200. public let result: AFResult<Value>
  201. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  202. public var value: Value? { return result.success }
  203. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  204. public var error: Error? { return result.failure }
  205. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  206. ///
  207. /// - Parameters:
  208. /// - request: The `URLRequest` sent to the server.
  209. /// - response: The `HTTPURLResponse` from the server.
  210. /// - temporaryURL: The temporary destinatio `URL` of the data returned from the server.
  211. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
  212. /// - resumeData: The resume `Data` generated if the request was cancelled.
  213. /// - metrics: The `URLSessionTaskMetrics` of the serialized response.
  214. /// - serializationDuration: The duration taken by serialization.
  215. /// - result: The `AFResult` of response serialization.
  216. public init(
  217. request: URLRequest?,
  218. response: HTTPURLResponse?,
  219. fileURL: URL?,
  220. resumeData: Data?,
  221. metrics: URLSessionTaskMetrics?,
  222. serializationDuration: TimeInterval,
  223. result: AFResult<Value>)
  224. {
  225. self.request = request
  226. self.response = response
  227. self.fileURL = fileURL
  228. self.resumeData = resumeData
  229. self.metrics = metrics
  230. self.serializationDuration = serializationDuration
  231. self.result = result
  232. }
  233. }
  234. // MARK: -
  235. extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
  236. /// The textual representation used when written to an output stream, which includes whether the result was a
  237. /// success or failure.
  238. public var description: String {
  239. return "\(result)"
  240. }
  241. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  242. /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
  243. /// actions, and the response serialization result.
  244. public var debugDescription: String {
  245. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  246. let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None"
  247. let responseDescription = response.map { (response) in
  248. let sortedHeaders = response.headers.sorted()
  249. return """
  250. [Status Code]: \(response.statusCode)
  251. [Headers]:
  252. \(sortedHeaders)
  253. """
  254. } ?? "nil"
  255. let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  256. let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
  257. return """
  258. [Request]: \(requestDescription)
  259. [Request Body]: \n\(requestBody)
  260. [Response]: \n\(responseDescription)
  261. [File URL]: \(fileURL?.path ?? "nil")
  262. [ResumeData]: \(resumeDataDescription)
  263. [Network Duration]: \(metricsDescription)
  264. [Serialization Duration]: \(serializationDuration)s
  265. [Result]: \(result)
  266. """
  267. }
  268. }
  269. // MARK: -
  270. extension DownloadResponse {
  271. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  272. /// result value as a parameter.
  273. ///
  274. /// Use the `map` method with a closure that does not throw. For example:
  275. ///
  276. /// let possibleData: DownloadResponse<Data> = ...
  277. /// let possibleInt = possibleData.map { $0.count }
  278. ///
  279. /// - parameter transform: A closure that takes the success value of the instance's result.
  280. ///
  281. /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
  282. /// result is a failure, returns a response wrapping the same failure.
  283. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> {
  284. return DownloadResponse<T>(
  285. request: request,
  286. response: response,
  287. fileURL: fileURL,
  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: response,
  312. fileURL: fileURL,
  313. resumeData: resumeData,
  314. metrics: metrics,
  315. serializationDuration: serializationDuration,
  316. result: result.flatMap(transform)
  317. )
  318. }
  319. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  320. ///
  321. /// Use the `mapError` function with a closure that does not throw. For example:
  322. ///
  323. /// let possibleData: DownloadResponse<Data> = ...
  324. /// let withMyError = possibleData.mapError { MyError.error($0) }
  325. ///
  326. /// - Parameter transform: A closure that takes the error of the instance.
  327. ///
  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: response,
  333. fileURL: fileURL,
  334. resumeData: resumeData,
  335. metrics: metrics,
  336. serializationDuration: serializationDuration,
  337. result: result.mapError(transform)
  338. )
  339. }
  340. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  341. ///
  342. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  343. ///
  344. /// let possibleData: DownloadResponse<Data> = ...
  345. /// let possibleObject = possibleData.flatMapError {
  346. /// try someFailableFunction(taking: $0)
  347. /// }
  348. ///
  349. /// - Parameter transform: A throwing closure that takes the error of the instance.
  350. ///
  351. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  352. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DownloadResponse {
  353. return DownloadResponse(
  354. request: request,
  355. response: response,
  356. fileURL: fileURL,
  357. resumeData: resumeData,
  358. metrics: metrics,
  359. serializationDuration: serializationDuration,
  360. result: result.flatMapError(transform)
  361. )
  362. }
  363. }