2
0

ResponseSerialization.swift 14 KB

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