ResponseSerialization.swift 13 KB

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