Response.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. /// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type.
  26. public typealias AFDataResponse<Success> = DataResponse<Success, AFError>
  27. /// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type.
  28. public typealias AFDownloadResponse<Success> = DownloadResponse<Success, AFError>
  29. /// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`.
  30. public struct DataResponse<Success, Failure: Error> {
  31. /// The URL request sent to the server.
  32. public let request: URLRequest?
  33. /// The server's response to the URL request.
  34. public let response: HTTPURLResponse?
  35. /// The data returned by the server.
  36. public let data: Data?
  37. /// The final metrics of the response.
  38. ///
  39. /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
  40. ///
  41. public let metrics: URLSessionTaskMetrics?
  42. /// The time taken to serialize the response.
  43. public let serializationDuration: TimeInterval
  44. /// The result of response serialization.
  45. public let result: Result<Success, Failure>
  46. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  47. public var value: Success? { result.success }
  48. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  49. public var error: Failure? { result.failure }
  50. /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization.
  51. ///
  52. /// - Parameters:
  53. /// - request: The `URLRequest` sent to the server.
  54. /// - response: The `HTTPURLResponse` from the server.
  55. /// - data: The `Data` returned by the server.
  56. /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`.
  57. /// - serializationDuration: The duration taken by serialization.
  58. /// - result: The `Result` of response serialization.
  59. public init(request: URLRequest?,
  60. response: HTTPURLResponse?,
  61. data: Data?,
  62. metrics: URLSessionTaskMetrics?,
  63. serializationDuration: TimeInterval,
  64. result: Result<Success, Failure>) {
  65. self.request = request
  66. self.response = response
  67. self.data = data
  68. self.metrics = metrics
  69. self.serializationDuration = serializationDuration
  70. self.result = result
  71. }
  72. }
  73. // MARK: -
  74. extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
  75. /// The textual representation used when written to an output stream, which includes whether the result was a
  76. /// success or failure.
  77. public var description: String {
  78. "\(result)"
  79. }
  80. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  81. /// response, the server data, the duration of the network and serialization actions, and the response serialization
  82. /// result.
  83. public var debugDescription: String {
  84. let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
  85. let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None"
  86. let responseDescription = response.map { response in
  87. let sortedHeaders = response.headers.sorted()
  88. return """
  89. [Status Code]: \(response.statusCode)
  90. [Headers]:
  91. \(sortedHeaders)
  92. """
  93. } ?? "nil"
  94. let responseBody = data.map { String(decoding: $0, as: UTF8.self) } ?? "None"
  95. let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
  96. return """
  97. [Request]: \(requestDescription)
  98. [Request Body]: \n\(requestBody)
  99. [Response]: \n\(responseDescription)
  100. [Response Body]: \n\(responseBody)
  101. [Data]: \(data?.description ?? "None")
  102. [Network Duration]: \(metricsDescription)
  103. [Serialization Duration]: \(serializationDuration)s
  104. [Result]: \(result)
  105. """
  106. }
  107. }
  108. // MARK: -
  109. extension DataResponse {
  110. /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
  111. /// result value as a parameter.
  112. ///
  113. /// Use the `map` method with a closure that does not throw. For example:
  114. ///
  115. /// let possibleData: DataResponse<Data> = ...
  116. /// let possibleInt = possibleData.map { $0.count }
  117. ///
  118. /// - parameter transform: A closure that takes the success value of the instance's result.
  119. ///
  120. /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
  121. /// result is a failure, returns a response wrapping the same failure.
  122. public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure> {
  123. DataResponse<NewSuccess, Failure>(request: request,
  124. response: response,
  125. data: data,
  126. metrics: metrics,
  127. serializationDuration: serializationDuration,
  128. result: result.map(transform))
  129. }
  130. /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
  131. /// value as a parameter.
  132. ///
  133. /// Use the `tryMap` method with a closure that may throw an error. For example:
  134. ///
  135. /// let possibleData: DataResponse<Data> = ...
  136. /// let possibleObject = possibleData.tryMap {
  137. /// try JSONSerialization.jsonObject(with: $0)
  138. /// }
  139. ///
  140. /// - parameter transform: A closure that takes the success value of the instance's result.
  141. ///
  142. /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
  143. /// result is a failure, returns the same failure.
  144. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error> {
  145. DataResponse<NewSuccess, Error>(request: request,
  146. response: response,
  147. data: data,
  148. metrics: metrics,
  149. serializationDuration: serializationDuration,
  150. result: result.tryMap(transform))
  151. }
  152. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  153. ///
  154. /// Use the `mapError` function with a closure that does not throw. For example:
  155. ///
  156. /// let possibleData: DataResponse<Data> = ...
  157. /// let withMyError = possibleData.mapError { MyError.error($0) }
  158. ///
  159. /// - Parameter transform: A closure that takes the error of the instance.
  160. ///
  161. /// - Returns: A `DataResponse` instance containing the result of the transform.
  162. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> {
  163. DataResponse<Success, NewFailure>(request: request,
  164. response: response,
  165. data: data,
  166. metrics: metrics,
  167. serializationDuration: serializationDuration,
  168. result: result.mapError(transform))
  169. }
  170. /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
  171. ///
  172. /// Use the `tryMapError` function with a closure that may throw an error. For example:
  173. ///
  174. /// let possibleData: DataResponse<Data> = ...
  175. /// let possibleObject = possibleData.tryMapError {
  176. /// try someFailableFunction(taking: $0)
  177. /// }
  178. ///
  179. /// - Parameter transform: A throwing closure that takes the error of the instance.
  180. ///
  181. /// - Returns: A `DataResponse` instance containing the result of the transform.
  182. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> {
  183. DataResponse<Success, Error>(request: request,
  184. response: response,
  185. data: data,
  186. metrics: metrics,
  187. serializationDuration: serializationDuration,
  188. result: result.tryMapError(transform))
  189. }
  190. }
  191. // MARK: -
  192. /// Used to store all data associated with a serialized response of a download request.
  193. public struct DownloadResponse<Success, Failure: Error> {
  194. /// The URL request sent to the server.
  195. public let request: URLRequest?
  196. /// The server's response to the URL request.
  197. public let response: HTTPURLResponse?
  198. /// The final destination URL of the data returned from the server after it is moved.
  199. public let fileURL: URL?
  200. /// The resume data generated if the request was cancelled.
  201. public let resumeData: Data?
  202. /// The final metrics of the response.
  203. ///
  204. /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
  205. ///
  206. public let metrics: URLSessionTaskMetrics?
  207. /// The time taken to serialize the response.
  208. public let serializationDuration: TimeInterval
  209. /// The result of response serialization.
  210. public let result: Result<Success, Failure>
  211. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  212. public var value: Success? { result.success }
  213. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  214. public var error: Failure? { result.failure }
  215. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  216. ///
  217. /// - Parameters:
  218. /// - request: The `URLRequest` sent to the server.
  219. /// - response: The `HTTPURLResponse` from the server.
  220. /// - temporaryURL: The temporary destination `URL` of the data returned from the server.
  221. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
  222. /// - resumeData: The resume `Data` generated if the request was cancelled.
  223. /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`.
  224. /// - serializationDuration: The duration taken by serialization.
  225. /// - result: The `Result` of response serialization.
  226. public init(request: URLRequest?,
  227. response: HTTPURLResponse?,
  228. fileURL: URL?,
  229. resumeData: Data?,
  230. metrics: URLSessionTaskMetrics?,
  231. serializationDuration: TimeInterval,
  232. result: Result<Success, Failure>) {
  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. "\(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. DownloadResponse<NewSuccess, Failure>(request: request,
  293. response: response,
  294. fileURL: fileURL,
  295. resumeData: resumeData,
  296. metrics: metrics,
  297. serializationDuration: serializationDuration,
  298. result: result.map(transform))
  299. }
  300. /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
  301. /// result value as a parameter.
  302. ///
  303. /// Use the `tryMap` method with a closure that may throw an error. For example:
  304. ///
  305. /// let possibleData: DownloadResponse<Data> = ...
  306. /// let possibleObject = possibleData.tryMap {
  307. /// try JSONSerialization.jsonObject(with: $0)
  308. /// }
  309. ///
  310. /// - parameter transform: A closure that takes the success value of the instance's result.
  311. ///
  312. /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
  313. /// instance's result is a failure, returns the same failure.
  314. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error> {
  315. DownloadResponse<NewSuccess, Error>(request: request,
  316. response: response,
  317. fileURL: fileURL,
  318. resumeData: resumeData,
  319. metrics: metrics,
  320. serializationDuration: serializationDuration,
  321. result: result.tryMap(transform))
  322. }
  323. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  324. ///
  325. /// Use the `mapError` function with a closure that does not throw. For example:
  326. ///
  327. /// let possibleData: DownloadResponse<Data> = ...
  328. /// let withMyError = possibleData.mapError { MyError.error($0) }
  329. ///
  330. /// - Parameter transform: A closure that takes the error of the instance.
  331. ///
  332. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  333. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> {
  334. DownloadResponse<Success, NewFailure>(request: request,
  335. response: response,
  336. fileURL: fileURL,
  337. resumeData: resumeData,
  338. metrics: metrics,
  339. serializationDuration: serializationDuration,
  340. result: result.mapError(transform))
  341. }
  342. /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
  343. ///
  344. /// Use the `tryMapError` function with a closure that may throw an error. For example:
  345. ///
  346. /// let possibleData: DownloadResponse<Data> = ...
  347. /// let possibleObject = possibleData.tryMapError {
  348. /// try someFailableFunction(taking: $0)
  349. /// }
  350. ///
  351. /// - Parameter transform: A throwing closure that takes the error of the instance.
  352. ///
  353. /// - Returns: A `DownloadResponse` instance containing the result of the transform.
  354. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> {
  355. DownloadResponse<Success, Error>(request: request,
  356. response: response,
  357. fileURL: fileURL,
  358. resumeData: resumeData,
  359. metrics: metrics,
  360. serializationDuration: serializationDuration,
  361. result: result.tryMapError(transform))
  362. }
  363. }