ResponseSerialization.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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?, Error?) -> Result<SerializedObject> { 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>: 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 = ErrorType
  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?, Error?) -> Result<Value>
  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: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) {
  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: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> 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: @escaping (Response<T.SerializedObject>) -> 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>(
  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> {
  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. return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
  127. }
  128. return .success(validData)
  129. }
  130. }
  131. /// Adds a handler to be called once the request has finished.
  132. ///
  133. /// - parameter completionHandler: The code to be executed once the request has finished.
  134. ///
  135. /// - returns: The request.
  136. @discardableResult
  137. public func responseData(queue: DispatchQueue? = nil, completionHandler: @escaping (Response<Data>) -> Void) -> Self {
  138. return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
  139. }
  140. }
  141. // MARK: - String
  142. extension Request {
  143. /// Creates a response serializer that returns a string initialized from the response data with the specified
  144. /// string encoding.
  145. ///
  146. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  147. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  148. ///
  149. /// - returns: A string response serializer.
  150. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> ResponseSerializer<String> {
  151. return ResponseSerializer { _, response, data, error in
  152. guard error == nil else { return .failure(error!) }
  153. if let response = response, response.statusCode == 204 { return .success("") }
  154. guard let validData = data else {
  155. return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
  156. }
  157. var convertedEncoding = encoding
  158. if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil {
  159. convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
  160. CFStringConvertIANACharSetNameToEncoding(encodingName))
  161. )
  162. }
  163. let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1
  164. if let string = String(data: validData, encoding: actualEncoding) {
  165. return .success(string)
  166. } else {
  167. return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)))
  168. }
  169. }
  170. }
  171. /// Adds a handler to be called once the request has finished.
  172. ///
  173. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  174. /// server response, falling back to the default HTTP default character set,
  175. /// ISO-8859-1.
  176. /// - parameter completionHandler: A closure to be executed once the request has finished.
  177. ///
  178. /// - returns: The request.
  179. @discardableResult
  180. public func responseString(
  181. queue: DispatchQueue? = nil,
  182. encoding: String.Encoding? = nil,
  183. completionHandler: @escaping (Response<String>) -> Void)
  184. -> Self
  185. {
  186. return response(
  187. queue: queue,
  188. responseSerializer: Request.stringResponseSerializer(encoding: encoding),
  189. completionHandler: completionHandler
  190. )
  191. }
  192. }
  193. // MARK: - JSON
  194. extension Request {
  195. /// Creates a response serializer that returns a JSON object constructed from the response data using
  196. /// `JSONSerialization` with the specified reading options.
  197. ///
  198. /// - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  199. ///
  200. /// - returns: A JSON object response serializer.
  201. public static func JSONResponseSerializer(
  202. options: JSONSerialization.ReadingOptions = .allowFragments)
  203. -> ResponseSerializer<Any>
  204. {
  205. return ResponseSerializer { _, response, data, error in
  206. guard error == nil else { return .failure(error!) }
  207. if let response = response, response.statusCode == 204 { return .success(NSNull()) }
  208. guard let validData = data, validData.count > 0 else {
  209. return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
  210. }
  211. do {
  212. let json = try JSONSerialization.jsonObject(with: validData, options: options)
  213. return .success(json)
  214. } catch {
  215. return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
  216. }
  217. }
  218. }
  219. /// Adds a handler to be called once the request has finished.
  220. ///
  221. /// - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  222. /// - parameter completionHandler: A closure to be executed once the request has finished.
  223. ///
  224. /// - returns: The request.
  225. @discardableResult
  226. public func responseJSON(
  227. queue: DispatchQueue? = nil,
  228. options: JSONSerialization.ReadingOptions = .allowFragments,
  229. completionHandler: @escaping (Response<Any>) -> Void)
  230. -> Self
  231. {
  232. return response(
  233. queue: queue,
  234. responseSerializer: Request.JSONResponseSerializer(options: options),
  235. completionHandler: completionHandler
  236. )
  237. }
  238. }
  239. // MARK: - Property List
  240. extension Request {
  241. /// Creates a response serializer that returns an object constructed from the response data using
  242. /// `PropertyListSerialization` with the specified reading options.
  243. ///
  244. /// - parameter options: The property list reading options. `PropertyListReadOptions()` by default.
  245. ///
  246. /// - returns: A property list object response serializer.
  247. public static func propertyListResponseSerializer(
  248. options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions())
  249. -> ResponseSerializer<Any>
  250. {
  251. return ResponseSerializer { _, response, data, error in
  252. guard error == nil else { return .failure(error!) }
  253. if let response = response, response.statusCode == 204 { return .success(NSNull()) }
  254. guard let validData = data, validData.count > 0 else {
  255. return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
  256. }
  257. do {
  258. let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
  259. return .success(plist)
  260. } catch {
  261. return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error)))
  262. }
  263. }
  264. }
  265. /// Adds a handler to be called once the request has finished.
  266. ///
  267. /// - parameter options: The property list reading options. `0` by default.
  268. /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
  269. /// arguments: the URL request, the URL response, the server data and the result
  270. /// produced while creating the property list.
  271. ///
  272. /// - returns: The request.
  273. @discardableResult
  274. public func responsePropertyList(
  275. queue: DispatchQueue? = nil,
  276. options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions(),
  277. completionHandler: @escaping (Response<Any>) -> Void)
  278. -> Self
  279. {
  280. return response(
  281. queue: queue,
  282. responseSerializer: Request.propertyListResponseSerializer(options: options),
  283. completionHandler: completionHandler
  284. )
  285. }
  286. }