2
0

Response.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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.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 `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. /// - Returns: A `DataResponse` instance containing the result of the transform.
  154. public func mapError<E: Error>(_ transform: (Error) -> E) -> DataResponse {
  155. return DataResponse(request: request,
  156. response: self.response,
  157. data: data,
  158. metrics: metrics,
  159. serializationDuration: serializationDuration,
  160. result: result.mapError(transform))
  161. }
  162. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  163. ///
  164. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  165. ///
  166. /// let possibleData: DataResponse<Data> = ...
  167. /// let possibleObject = possibleData.flatMapError {
  168. /// try someFailableFunction(taking: $0)
  169. /// }
  170. ///
  171. /// - Parameter transform: A throwing closure that takes the error of the instance.
  172. ///
  173. /// - Returns: A `DataResponse` instance containing the result of the transform.
  174. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DataResponse {
  175. return DataResponse(request: request,
  176. response: self.response,
  177. data: data,
  178. metrics: metrics,
  179. serializationDuration: serializationDuration,
  180. result: result.flatMapError(transform))
  181. }
  182. }
  183. // MARK: -
  184. /// Used to store all data associated with a serialized response of a download request.
  185. public struct DownloadResponse<Value> {
  186. /// The URL request sent to the server.
  187. public let request: URLRequest?
  188. /// The server's response to the URL request.
  189. public let response: HTTPURLResponse?
  190. /// The final destination URL of the data returned from the server after it is moved.
  191. public let fileURL: URL?
  192. /// The resume data generated if the request was cancelled.
  193. public let resumeData: Data?
  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. /// The result of response serialization.
  199. public let result: AFResult<Value>
  200. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  201. public var value: Value? { return result.value }
  202. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  203. public var error: Error? { return result.error }
  204. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  205. ///
  206. /// - Parameters:
  207. /// - request: The `URLRequest` sent to the server.
  208. /// - response: The `HTTPURLResponse` from the server.
  209. /// - temporaryURL: The temporary destinatio `URL` of the data returned from the server.
  210. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
  211. /// - resumeData: The resume `Data` generated if the request was cancelled.
  212. /// - metrics: The `URLSessionTaskMetrics` of the serialized response.
  213. /// - serializationDuration: The duration taken by serialization.
  214. /// - result: The `AFResult` of response serialization.
  215. public init(
  216. request: URLRequest?,
  217. response: HTTPURLResponse?,
  218. fileURL: URL?,
  219. resumeData: Data?,
  220. metrics: URLSessionTaskMetrics?,
  221. serializationDuration: TimeInterval,
  222. result: AFResult<Value>)
  223. {
  224. self.request = request
  225. self.response = response
  226. self.fileURL = fileURL
  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)"
  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 durations of the network and serialization
  242. /// actions, and the response serialization result.
  243. public var debugDescription: String {
  244. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  245. let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None"
  246. let responseDescription = response.map { (response) in
  247. let sortedHeaders = response.headers.sorted()
  248. return """
  249. [Status Code]: \(response.statusCode)
  250. [Headers]:
  251. \(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. [Request Body]: \n\(requestBody)
  259. [Response]: \n\(responseDescription)
  260. [File URL]: \(fileURL?.path ?? "nil")
  261. [ResumeData]: \(resumeDataDescription)
  262. [Network Duration]: \(metricsDescription)
  263. [Serialization Duration]: \(serializationDuration)s
  264. [Result]: \(result)
  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: response,
  286. fileURL: fileURL,
  287. resumeData: resumeData,
  288. metrics: metrics,
  289. serializationDuration: serializationDuration,
  290. result: result.map(transform)
  291. )
  292. }
  293. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  294. /// result value as a parameter.
  295. ///
  296. /// Use the `flatMap` method with a closure that may throw an error. For example:
  297. ///
  298. /// let possibleData: DownloadResponse<Data> = ...
  299. /// let possibleObject = possibleData.flatMap {
  300. /// try JSONSerialization.jsonObject(with: $0)
  301. /// }
  302. ///
  303. /// - parameter transform: A closure that takes the success value of the instance's result.
  304. ///
  305. /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
  306. /// instance's result is a failure, returns the same failure.
  307. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> {
  308. return DownloadResponse<T>(
  309. request: request,
  310. response: response,
  311. fileURL: fileURL,
  312. resumeData: resumeData,
  313. metrics: metrics,
  314. serializationDuration: serializationDuration,
  315. result: result.flatMap(transform)
  316. )
  317. }
  318. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  319. ///
  320. /// Use the `mapError` function with a closure that does not throw. For example:
  321. ///
  322. /// let possibleData: DownloadResponse<Data> = ...
  323. /// let withMyError = possibleData.mapError { MyError.error($0) }
  324. ///
  325. /// - Parameter transform: A closure that takes the error of the instance.
  326. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  327. public func mapError<E: Error>(_ transform: (Error) -> E) -> DownloadResponse {
  328. return DownloadResponse(
  329. request: request,
  330. response: response,
  331. fileURL: fileURL,
  332. resumeData: resumeData,
  333. metrics: metrics,
  334. serializationDuration: serializationDuration,
  335. result: result.mapError(transform)
  336. )
  337. }
  338. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  339. ///
  340. /// Use the `flatMapError` function with a closure that may throw an error. For example:
  341. ///
  342. /// let possibleData: DownloadResponse<Data> = ...
  343. /// let possibleObject = possibleData.flatMapError {
  344. /// try someFailableFunction(taking: $0)
  345. /// }
  346. ///
  347. /// - Parameter transform: A throwing closure that takes the error of the instance.
  348. ///
  349. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  350. public func flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DownloadResponse {
  351. return DownloadResponse(
  352. request: request,
  353. response: response,
  354. fileURL: fileURL,
  355. resumeData: resumeData,
  356. metrics: metrics,
  357. serializationDuration: serializationDuration,
  358. result: result.flatMapError(transform)
  359. )
  360. }
  361. }