ResponseSerialization.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //
  2. // ResponseSerialization.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. // MARK: ResponseSerializer
  26. /// The type in which all response serializers must conform to in order to serialize a response.
  27. public protocol ResponseSerializerType {
  28. /// The type of serialized object to be created by this `ResponseSerializerType`.
  29. associatedtype SerializedObject
  30. /// The type of error to be created by this `ResponseSerializer` if serialization fails.
  31. associatedtype ErrorObject: Error
  32. /// A closure used by response handlers that takes a request, response, data and error and returns a result.
  33. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
  34. }
  35. // MARK: -
  36. /// A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
  37. public struct ResponseSerializer<Value, Error: Swift.Error>: ResponseSerializerType {
  38. /// The type of serialized object to be created by this `ResponseSerializer`.
  39. public typealias SerializedObject = Value
  40. /// The type of error to be created by this `ResponseSerializer` if serialization fails.
  41. public typealias ErrorObject = Error
  42. /// A closure used by response handlers that takes a request, response, data and error and returns a result.
  43. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, NSError?) -> Result<Value, Error>
  44. /// Initializes the `ResponseSerializer` instance with the given serialize response closure.
  45. ///
  46. /// - parameter serializeResponse: The closure used to serialize the response.
  47. ///
  48. /// - returns: The new generic response serializer instance.
  49. public init(serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, NSError?) -> Result<Value, Error>) {
  50. self.serializeResponse = serializeResponse
  51. }
  52. }
  53. // MARK: - Default
  54. extension Request {
  55. /// Adds a handler to be called once the request has finished.
  56. ///
  57. /// - parameter queue: The queue on which the completion handler is dispatched.
  58. /// - parameter completionHandler: The code to be executed once the request has finished.
  59. ///
  60. /// - returns: The request.
  61. @discardableResult
  62. public func response(
  63. queue: DispatchQueue? = nil,
  64. completionHandler: (URLRequest?, HTTPURLResponse?, Data?, NSError?) -> Void)
  65. -> Self
  66. {
  67. delegate.queue.addOperation {
  68. (queue ?? DispatchQueue.main).async {
  69. completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
  70. }
  71. }
  72. return self
  73. }
  74. /// Adds a handler to be called once the request has finished.
  75. ///
  76. /// - parameter queue: The queue on which the completion handler is dispatched.
  77. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  78. /// and data.
  79. /// - parameter completionHandler: The code to be executed once the request has finished.
  80. ///
  81. /// - returns: The request.
  82. @discardableResult
  83. public func response<T: ResponseSerializerType>(
  84. queue: DispatchQueue? = nil,
  85. responseSerializer: T,
  86. completionHandler: (Response<T.SerializedObject, T.ErrorObject>) -> Void)
  87. -> Self
  88. {
  89. delegate.queue.addOperation {
  90. let result = responseSerializer.serializeResponse(
  91. self.request,
  92. self.response,
  93. self.delegate.data,
  94. self.delegate.error
  95. )
  96. let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
  97. let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
  98. let timeline = Timeline(
  99. requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
  100. initialResponseTime: initialResponseTime,
  101. requestCompletedTime: requestCompletedTime,
  102. serializationCompletedTime: CFAbsoluteTimeGetCurrent()
  103. )
  104. let response = Response<T.SerializedObject, T.ErrorObject>(
  105. request: self.request,
  106. response: self.response,
  107. data: self.delegate.data,
  108. result: result,
  109. timeline: timeline
  110. )
  111. (queue ?? DispatchQueue.main).async { completionHandler(response) }
  112. }
  113. return self
  114. }
  115. }
  116. // MARK: - Data
  117. extension Request {
  118. /// Creates a response serializer that returns the associated data as-is.
  119. ///
  120. /// - returns: A data response serializer.
  121. public static func dataResponseSerializer() -> ResponseSerializer<Data, NSError> {
  122. return ResponseSerializer { _, response, data, error in
  123. guard error == nil else { return .failure(error!) }
  124. if let response = response, response.statusCode == 204 { return .success(Data()) }
  125. guard let validData = data else {
  126. let failureReason = "Data could not be serialized. Input data was nil."
  127. let error = NSError(code: .dataSerializationFailed, failureReason: failureReason)
  128. return .failure(error)
  129. }
  130. return .success(validData)
  131. }
  132. }
  133. /// Adds a handler to be called once the request has finished.
  134. ///
  135. /// - parameter completionHandler: The code to be executed once the request has finished.
  136. ///
  137. /// - returns: The request.
  138. @discardableResult
  139. public func responseData(queue: DispatchQueue? = nil, completionHandler: (Response<Data, NSError>) -> Void) -> Self {
  140. return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
  141. }
  142. }
  143. // MARK: - String
  144. extension Request {
  145. /// Creates a response serializer that returns a string initialized from the response data with the specified
  146. /// string encoding.
  147. ///
  148. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  149. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  150. ///
  151. /// - returns: A string response serializer.
  152. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> ResponseSerializer<String, NSError> {
  153. return ResponseSerializer { _, response, data, error in
  154. guard error == nil else { return .failure(error!) }
  155. if let response = response, response.statusCode == 204 { return .success("") }
  156. guard let validData = data else {
  157. let failureReason = "String could not be serialized. Input data was nil."
  158. let error = NSError(code: .stringSerializationFailed, failureReason: failureReason)
  159. return .failure(error)
  160. }
  161. var convertedEncoding = encoding
  162. if let encodingName = response?.textEncodingName, convertedEncoding == nil {
  163. convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
  164. CFStringConvertIANACharSetNameToEncoding(encodingName))
  165. )
  166. }
  167. let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1
  168. if let string = String(data: validData, encoding: actualEncoding) {
  169. return .success(string)
  170. } else {
  171. let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
  172. let error = NSError(code: .stringSerializationFailed, failureReason: failureReason)
  173. return .failure(error)
  174. }
  175. }
  176. }
  177. /// Adds a handler to be called once the request has finished.
  178. ///
  179. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  180. /// server response, falling back to the default HTTP default character set,
  181. /// ISO-8859-1.
  182. /// - parameter completionHandler: A closure to be executed once the request has finished.
  183. ///
  184. /// - returns: The request.
  185. @discardableResult
  186. public func responseString(
  187. queue: DispatchQueue? = nil,
  188. encoding: String.Encoding? = nil,
  189. completionHandler: (Response<String, NSError>) -> Void)
  190. -> Self
  191. {
  192. return response(
  193. queue: queue,
  194. responseSerializer: Request.stringResponseSerializer(encoding: encoding),
  195. completionHandler: completionHandler
  196. )
  197. }
  198. }
  199. // MARK: - JSON
  200. extension Request {
  201. /// Creates a response serializer that returns a JSON object constructed from the response data using
  202. /// `JSONSerialization` with the specified reading options.
  203. ///
  204. /// - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  205. ///
  206. /// - returns: A JSON object response serializer.
  207. public static func JSONResponseSerializer(
  208. options: JSONSerialization.ReadingOptions = .allowFragments)
  209. -> ResponseSerializer<AnyObject, NSError>
  210. {
  211. return ResponseSerializer { _, response, data, error in
  212. guard error == nil else { return .failure(error!) }
  213. if let response = response, response.statusCode == 204 { return .success(NSNull()) }
  214. guard let validData = data, validData.count > 0 else {
  215. let failureReason = "JSON could not be serialized. Input data was nil or zero length."
  216. let error = NSError(code: .jsonSerializationFailed, failureReason: failureReason)
  217. return .failure(error)
  218. }
  219. do {
  220. let JSON = try JSONSerialization.jsonObject(with: validData, options: options)
  221. return .success(JSON)
  222. } catch {
  223. return .failure(error as NSError)
  224. }
  225. }
  226. }
  227. /// Adds a handler to be called once the request has finished.
  228. ///
  229. /// - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  230. /// - parameter completionHandler: A closure to be executed once the request has finished.
  231. ///
  232. /// - returns: The request.
  233. @discardableResult
  234. public func responseJSON(
  235. queue: DispatchQueue? = nil,
  236. options: JSONSerialization.ReadingOptions = .allowFragments,
  237. completionHandler: (Response<AnyObject, NSError>) -> Void)
  238. -> Self
  239. {
  240. return response(
  241. queue: queue,
  242. responseSerializer: Request.JSONResponseSerializer(options: options),
  243. completionHandler: completionHandler
  244. )
  245. }
  246. }
  247. // MARK: - Property List
  248. extension Request {
  249. /// Creates a response serializer that returns an object constructed from the response data using
  250. /// `PropertyListSerialization` with the specified reading options.
  251. ///
  252. /// - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
  253. ///
  254. /// - returns: A property list object response serializer.
  255. public static func propertyListResponseSerializer(
  256. options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions())
  257. -> ResponseSerializer<AnyObject, NSError>
  258. {
  259. return ResponseSerializer { _, response, data, error in
  260. guard error == nil else { return .failure(error!) }
  261. if let response = response, response.statusCode == 204 { return .success(NSNull()) }
  262. guard let validData = data, validData.count > 0 else {
  263. let failureReason = "Property list could not be serialized. Input data was nil or zero length."
  264. let error = NSError(code: .propertyListSerializationFailed, failureReason: failureReason)
  265. return .failure(error)
  266. }
  267. do {
  268. let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
  269. return .success(plist)
  270. } catch {
  271. return .failure(error as NSError)
  272. }
  273. }
  274. }
  275. /// Adds a handler to be called once the request has finished.
  276. ///
  277. /// - parameter options: The property list reading options. `0` by default.
  278. /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
  279. /// arguments: the URL request, the URL response, the server data and the result
  280. /// produced while creating the property list.
  281. ///
  282. /// - returns: The request.
  283. @discardableResult
  284. public func responsePropertyList(
  285. queue: DispatchQueue? = nil,
  286. options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions(),
  287. completionHandler: (Response<AnyObject, NSError>) -> Void)
  288. -> Self
  289. {
  290. return response(
  291. queue: queue,
  292. responseSerializer: Request.propertyListResponseSerializer(options: options),
  293. completionHandler: completionHandler
  294. )
  295. }
  296. }