ResponseSerialization.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. @discardableResult
  91. public func response<T: ResponseSerializerType>(
  92. queue: DispatchQueue? = nil,
  93. responseSerializer: T,
  94. completionHandler: (Response<T.SerializedObject, T.ErrorObject>) -> Void)
  95. -> Self
  96. {
  97. delegate.queue.addOperation {
  98. let result = responseSerializer.serializeResponse(
  99. self.request,
  100. self.response,
  101. self.delegate.data,
  102. self.delegate.error
  103. )
  104. let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
  105. let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
  106. let timeline = Timeline(
  107. requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
  108. initialResponseTime: initialResponseTime,
  109. requestCompletedTime: requestCompletedTime,
  110. serializationCompletedTime: CFAbsoluteTimeGetCurrent()
  111. )
  112. let response = Response<T.SerializedObject, T.ErrorObject>(
  113. request: self.request,
  114. response: self.response,
  115. data: self.delegate.data,
  116. result: result,
  117. timeline: timeline
  118. )
  119. (queue ?? DispatchQueue.main).async { completionHandler(response) }
  120. }
  121. return self
  122. }
  123. }
  124. // MARK: - Data
  125. extension Request {
  126. /**
  127. Creates a response serializer that returns the associated data as-is.
  128. - returns: A data response serializer.
  129. */
  130. public static func dataResponseSerializer() -> ResponseSerializer<Data, NSError> {
  131. return ResponseSerializer { _, response, data, error in
  132. guard error == nil else { return .failure(error!) }
  133. if let response = response, response.statusCode == 204 { return .success(Data()) }
  134. guard let validData = data else {
  135. let failureReason = "Data could not be serialized. Input data was nil."
  136. let error = Error.error(code: .dataSerializationFailed, failureReason: failureReason)
  137. return .failure(error)
  138. }
  139. return .success(validData)
  140. }
  141. }
  142. /**
  143. Adds a handler to be called once the request has finished.
  144. - parameter completionHandler: The code to be executed once the request has finished.
  145. - returns: The request.
  146. */
  147. @discardableResult
  148. public func responseData(
  149. queue: DispatchQueue? = nil,
  150. completionHandler: (Response<Data, NSError>) -> Void)
  151. -> Self
  152. {
  153. return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
  154. }
  155. }
  156. // MARK: - String
  157. extension Request {
  158. /**
  159. Creates a response serializer that returns a string initialized from the response data with the specified
  160. string encoding.
  161. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  162. response, falling back to the default HTTP default character set, ISO-8859-1.
  163. - returns: A string response serializer.
  164. */
  165. public static func stringResponseSerializer(
  166. encoding: String.Encoding? = nil)
  167. -> ResponseSerializer<String, NSError>
  168. {
  169. return ResponseSerializer { _, response, data, error in
  170. guard error == nil else { return .failure(error!) }
  171. if let response = response, response.statusCode == 204 { return .success("") }
  172. guard let validData = data else {
  173. let failureReason = "String could not be serialized. Input data was nil."
  174. let error = Error.error(code: .stringSerializationFailed, failureReason: failureReason)
  175. return .failure(error)
  176. }
  177. var convertedEncoding = encoding
  178. if let encodingName = response?.textEncodingName, convertedEncoding == nil {
  179. convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
  180. CFStringConvertIANACharSetNameToEncoding(encodingName))
  181. )
  182. }
  183. let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1
  184. if let string = String(data: validData, encoding: actualEncoding) {
  185. return .success(string)
  186. } else {
  187. let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
  188. let error = Error.error(code: .stringSerializationFailed, failureReason: failureReason)
  189. return .failure(error)
  190. }
  191. }
  192. }
  193. /**
  194. Adds a handler to be called once the request has finished.
  195. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  196. server response, falling back to the default HTTP default character set,
  197. ISO-8859-1.
  198. - parameter completionHandler: A closure to be executed once the request has finished.
  199. - returns: The request.
  200. */
  201. @discardableResult
  202. public func responseString(
  203. queue: DispatchQueue? = nil,
  204. encoding: String.Encoding? = nil,
  205. completionHandler: (Response<String, NSError>) -> Void)
  206. -> Self
  207. {
  208. return response(
  209. queue: queue,
  210. responseSerializer: Request.stringResponseSerializer(encoding: encoding),
  211. completionHandler: completionHandler
  212. )
  213. }
  214. }
  215. // MARK: - JSON
  216. extension Request {
  217. /**
  218. Creates a response serializer that returns a JSON object constructed from the response data using
  219. `NSJSONSerialization` with the specified reading options.
  220. - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  221. - returns: A JSON object response serializer.
  222. */
  223. public static func JSONResponseSerializer(
  224. options: JSONSerialization.ReadingOptions = .allowFragments)
  225. -> ResponseSerializer<AnyObject, NSError>
  226. {
  227. return ResponseSerializer { _, response, data, error in
  228. guard error == nil else { return .failure(error!) }
  229. if let response = response, response.statusCode == 204 { return .success(NSNull()) }
  230. guard let validData = data, validData.count > 0 else {
  231. let failureReason = "JSON could not be serialized. Input data was nil or zero length."
  232. let error = Error.error(code: .jsonSerializationFailed, failureReason: failureReason)
  233. return .failure(error)
  234. }
  235. do {
  236. let JSON = try JSONSerialization.jsonObject(with: validData, options: options)
  237. return .success(JSON)
  238. } catch {
  239. return .failure(error as NSError)
  240. }
  241. }
  242. }
  243. /**
  244. Adds a handler to be called once the request has finished.
  245. - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  246. - parameter completionHandler: A closure to be executed once the request has finished.
  247. - returns: The request.
  248. */
  249. @discardableResult
  250. public func responseJSON(
  251. queue: DispatchQueue? = nil,
  252. options: JSONSerialization.ReadingOptions = .allowFragments,
  253. completionHandler: (Response<AnyObject, NSError>) -> Void)
  254. -> Self
  255. {
  256. return response(
  257. queue: queue,
  258. responseSerializer: Request.JSONResponseSerializer(options: options),
  259. completionHandler: completionHandler
  260. )
  261. }
  262. }
  263. // MARK: - Property List
  264. extension Request {
  265. /**
  266. Creates a response serializer that returns an object constructed from the response data using
  267. `NSPropertyListSerialization` with the specified reading options.
  268. - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
  269. - returns: A property list object response serializer.
  270. */
  271. public static func propertyListResponseSerializer(
  272. options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions())
  273. -> ResponseSerializer<AnyObject, NSError>
  274. {
  275. return ResponseSerializer { _, response, data, error in
  276. guard error == nil else { return .failure(error!) }
  277. if let response = response, response.statusCode == 204 { return .success(NSNull()) }
  278. guard let validData = data, validData.count > 0 else {
  279. let failureReason = "Property list could not be serialized. Input data was nil or zero length."
  280. let error = Error.error(code: .propertyListSerializationFailed, failureReason: failureReason)
  281. return .failure(error)
  282. }
  283. do {
  284. let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
  285. return .success(plist)
  286. } catch {
  287. return .failure(error as NSError)
  288. }
  289. }
  290. }
  291. /**
  292. Adds a handler to be called once the request has finished.
  293. - parameter options: The property list reading options. `0` by default.
  294. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
  295. arguments: the URL request, the URL response, the server data and the result
  296. produced while creating the property list.
  297. - returns: The request.
  298. */
  299. @discardableResult
  300. public func responsePropertyList(
  301. queue: DispatchQueue? = nil,
  302. options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions(),
  303. completionHandler: (Response<AnyObject, NSError>) -> Void)
  304. -> Self
  305. {
  306. return response(
  307. queue: queue,
  308. responseSerializer: Request.propertyListResponseSerializer(options: options),
  309. completionHandler: completionHandler
  310. )
  311. }
  312. }