Response.swift 10 KB

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