Response.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. //
  2. // Response.swift
  3. //
  4. // Copyright (c) 2014-2016 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 an non-serialized response of a data or upload request.
  26. public struct DefaultDataResponse {
  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 error encountered while executing or validating the request.
  34. public let error: Error?
  35. /// The timeline of the complete lifecycle of the request.
  36. public let timeline: Timeline
  37. var _metrics: AnyObject?
  38. /// Creates a `DefaultDataResponse` instance from the specified parameters.
  39. ///
  40. /// - Parameters:
  41. /// - request: The URL request sent to the server.
  42. /// - response: The server's response to the URL request.
  43. /// - data: The data returned by the server.
  44. /// - error: The error encountered while executing or validating the request.
  45. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default.
  46. /// - metrics: The task metrics containing the request / response statistics. `nil` by default.
  47. public init(
  48. request: URLRequest?,
  49. response: HTTPURLResponse?,
  50. data: Data?,
  51. error: Error?,
  52. timeline: Timeline = Timeline(),
  53. metrics: AnyObject? = nil)
  54. {
  55. self.request = request
  56. self.response = response
  57. self.data = data
  58. self.error = error
  59. self.timeline = timeline
  60. }
  61. }
  62. // MARK: -
  63. /// Used to store all data associated with a serialized response of a data or upload request.
  64. public struct DataResponse<Value> {
  65. /// The URL request sent to the server.
  66. public let request: URLRequest?
  67. /// The server's response to the URL request.
  68. public let response: HTTPURLResponse?
  69. /// The data returned by the server.
  70. public let data: Data?
  71. /// The result of response serialization.
  72. public let result: Result<Value>
  73. /// The timeline of the complete lifecycle of the request.
  74. public let timeline: Timeline
  75. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  76. public var value: Value? { return result.value }
  77. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  78. public var error: Error? { return result.error }
  79. var _metrics: AnyObject?
  80. /// Creates a `DataResponse` instance with the specified parameters derived from response serialization.
  81. ///
  82. /// - parameter request: The URL request sent to the server.
  83. /// - parameter response: The server's response to the URL request.
  84. /// - parameter data: The data returned by the server.
  85. /// - parameter result: The result of response serialization.
  86. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
  87. ///
  88. /// - returns: The new `DataResponse` instance.
  89. public init(
  90. request: URLRequest?,
  91. response: HTTPURLResponse?,
  92. data: Data?,
  93. result: Result<Value>,
  94. timeline: Timeline = Timeline())
  95. {
  96. self.request = request
  97. self.response = response
  98. self.data = data
  99. self.result = result
  100. self.timeline = timeline
  101. }
  102. }
  103. // MARK: -
  104. extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
  105. /// The textual representation used when written to an output stream, which includes whether the result was a
  106. /// success or failure.
  107. public var description: String {
  108. return result.debugDescription
  109. }
  110. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  111. /// response, the server data, the response serialization result and the timeline.
  112. public var debugDescription: String {
  113. var output: [String] = []
  114. output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
  115. output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
  116. output.append("[Data]: \(data?.count ?? 0) bytes")
  117. output.append("[Result]: \(result.debugDescription)")
  118. output.append("[Timeline]: \(timeline.debugDescription)")
  119. return output.joined(separator: "\n")
  120. }
  121. }
  122. // MARK: -
  123. /// Used to store all data associated with an non-serialized response of a download request.
  124. public struct DefaultDownloadResponse {
  125. /// The URL request sent to the server.
  126. public let request: URLRequest?
  127. /// The server's response to the URL request.
  128. public let response: HTTPURLResponse?
  129. /// The temporary destination URL of the data returned from the server.
  130. public let temporaryURL: URL?
  131. /// The final destination URL of the data returned from the server if it was moved.
  132. public let destinationURL: URL?
  133. /// The resume data generated if the request was cancelled.
  134. public let resumeData: Data?
  135. /// The error encountered while executing or validating the request.
  136. public let error: Error?
  137. /// The timeline of the complete lifecycle of the request.
  138. public let timeline: Timeline
  139. var _metrics: AnyObject?
  140. /// Creates a `DefaultDownloadResponse` instance from the specified parameters.
  141. ///
  142. /// - Parameters:
  143. /// - request: The URL request sent to the server.
  144. /// - response: The server's response to the URL request.
  145. /// - temporaryURL: The temporary destination URL of the data returned from the server.
  146. /// - destinationURL: The final destination URL of the data returned from the server if it was moved.
  147. /// - resumeData: The resume data generated if the request was cancelled.
  148. /// - error: The error encountered while executing or validating the request.
  149. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default.
  150. /// - metrics: The task metrics containing the request / response statistics. `nil` by default.
  151. public init(
  152. request: URLRequest?,
  153. response: HTTPURLResponse?,
  154. temporaryURL: URL?,
  155. destinationURL: URL?,
  156. resumeData: Data?,
  157. error: Error?,
  158. timeline: Timeline = Timeline(),
  159. metrics: AnyObject? = nil)
  160. {
  161. self.request = request
  162. self.response = response
  163. self.temporaryURL = temporaryURL
  164. self.destinationURL = destinationURL
  165. self.resumeData = resumeData
  166. self.error = error
  167. self.timeline = timeline
  168. }
  169. }
  170. // MARK: -
  171. /// Used to store all data associated with a serialized response of a download request.
  172. public struct DownloadResponse<Value> {
  173. /// The URL request sent to the server.
  174. public let request: URLRequest?
  175. /// The server's response to the URL request.
  176. public let response: HTTPURLResponse?
  177. /// The temporary destination URL of the data returned from the server.
  178. public let temporaryURL: URL?
  179. /// The final destination URL of the data returned from the server if it was moved.
  180. public let destinationURL: URL?
  181. /// The resume data generated if the request was cancelled.
  182. public let resumeData: Data?
  183. /// The result of response serialization.
  184. public let result: Result<Value>
  185. /// The timeline of the complete lifecycle of the request.
  186. public let timeline: Timeline
  187. /// Returns the associated value of the result if it is a success, `nil` otherwise.
  188. public var value: Value? { return result.value }
  189. /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
  190. public var error: Error? { return result.error }
  191. var _metrics: AnyObject?
  192. /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
  193. ///
  194. /// - parameter request: The URL request sent to the server.
  195. /// - parameter response: The server's response to the URL request.
  196. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server.
  197. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved.
  198. /// - parameter resumeData: The resume data generated if the request was cancelled.
  199. /// - parameter result: The result of response serialization.
  200. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
  201. ///
  202. /// - returns: The new `DownloadResponse` instance.
  203. public init(
  204. request: URLRequest?,
  205. response: HTTPURLResponse?,
  206. temporaryURL: URL?,
  207. destinationURL: URL?,
  208. resumeData: Data?,
  209. result: Result<Value>,
  210. timeline: Timeline = Timeline())
  211. {
  212. self.request = request
  213. self.response = response
  214. self.temporaryURL = temporaryURL
  215. self.destinationURL = destinationURL
  216. self.resumeData = resumeData
  217. self.result = result
  218. self.timeline = timeline
  219. }
  220. }
  221. // MARK: -
  222. extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
  223. /// The textual representation used when written to an output stream, which includes whether the result was a
  224. /// success or failure.
  225. public var description: String {
  226. return result.debugDescription
  227. }
  228. /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
  229. /// response, the temporary and destination URLs, the resume data, the response serialization result and the
  230. /// timeline.
  231. public var debugDescription: String {
  232. var output: [String] = []
  233. output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
  234. output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
  235. output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")")
  236. output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")")
  237. output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes")
  238. output.append("[Result]: \(result.debugDescription)")
  239. output.append("[Timeline]: \(timeline.debugDescription)")
  240. return output.joined(separator: "\n")
  241. }
  242. }
  243. // MARK: -
  244. protocol Response {
  245. /// The task metrics containing the request / response statistics.
  246. var _metrics: AnyObject? { get set }
  247. mutating func add(_ metrics: AnyObject?)
  248. }
  249. extension Response {
  250. mutating func add(_ metrics: AnyObject?) {
  251. #if !os(watchOS)
  252. guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return }
  253. guard let metrics = metrics as? URLSessionTaskMetrics else { return }
  254. _metrics = metrics
  255. #endif
  256. }
  257. }
  258. // MARK: -
  259. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
  260. extension DefaultDataResponse: Response {
  261. #if !os(watchOS)
  262. /// The task metrics containing the request / response statistics.
  263. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
  264. #endif
  265. }
  266. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
  267. extension DataResponse: Response {
  268. #if !os(watchOS)
  269. /// The task metrics containing the request / response statistics.
  270. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
  271. #endif
  272. }
  273. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
  274. extension DefaultDownloadResponse: Response {
  275. #if !os(watchOS)
  276. /// The task metrics containing the request / response statistics.
  277. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
  278. #endif
  279. }
  280. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
  281. extension DownloadResponse: Response {
  282. #if !os(watchOS)
  283. /// The task metrics containing the request / response statistics.
  284. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
  285. #endif
  286. }