ResponseSerialization.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. // ResponseSerialization.swift
  2. //
  3. // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. // MARK: ResponseSerializer
  24. /**
  25. The type in which all response serializers must conform to in order to serialize a response.
  26. */
  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: ErrorType
  32. /**
  33. A closure used by response handlers that takes a request, response, data and error and returns a result.
  34. */
  35. var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
  36. }
  37. // MARK: -
  38. /**
  39. A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
  40. */
  41. public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
  42. /// The type of serialized object to be created by this `ResponseSerializer`.
  43. public typealias SerializedObject = Value
  44. /// The type of error to be created by this `ResponseSerializer` if serialization fails.
  45. public typealias ErrorObject = Error
  46. /**
  47. A closure used by response handlers that takes a request, response, data and error and returns a result.
  48. */
  49. public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
  50. /**
  51. Initializes the `ResponseSerializer` instance with the given serialize response closure.
  52. - parameter serializeResponse: The closure used to serialize the response.
  53. - returns: The new generic response serializer instance.
  54. */
  55. public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
  56. self.serializeResponse = serializeResponse
  57. }
  58. }
  59. // MARK: - Default
  60. extension Request {
  61. /**
  62. Adds a handler to be called once the request has finished.
  63. - parameter queue: The queue on which the completion handler is dispatched.
  64. - parameter completionHandler: The code to be executed once the request has finished.
  65. - returns: The request.
  66. */
  67. public func response(
  68. queue queue: dispatch_queue_t? = nil,
  69. completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
  70. -> Self
  71. {
  72. delegate.queue.addOperationWithBlock {
  73. dispatch_async(queue ?? dispatch_get_main_queue()) {
  74. completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
  75. }
  76. }
  77. return self
  78. }
  79. /**
  80. Adds a handler to be called once the request has finished.
  81. - parameter queue: The queue on which the completion handler is dispatched.
  82. - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  83. and data.
  84. - parameter completionHandler: The code to be executed once the request has finished.
  85. - returns: The request.
  86. */
  87. public func response<T: ResponseSerializerType>(
  88. queue queue: dispatch_queue_t? = nil,
  89. responseSerializer: T,
  90. completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
  91. -> Self
  92. {
  93. delegate.queue.addOperationWithBlock {
  94. let result = responseSerializer.serializeResponse(
  95. self.request,
  96. self.response,
  97. self.delegate.data,
  98. self.delegate.error
  99. )
  100. let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
  101. let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
  102. let timeline = Timeline(
  103. requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
  104. initialResponseTime: initialResponseTime,
  105. requestCompletedTime: requestCompletedTime,
  106. serializationCompletedTime: CFAbsoluteTimeGetCurrent()
  107. )
  108. let response = Response<T.SerializedObject, T.ErrorObject>(
  109. request: self.request,
  110. response: self.response,
  111. data: self.delegate.data,
  112. result: result,
  113. timeline: timeline
  114. )
  115. dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
  116. }
  117. return self
  118. }
  119. }
  120. // MARK: - Data
  121. extension Request {
  122. /**
  123. Creates a response serializer that returns the associated data as-is.
  124. - returns: A data response serializer.
  125. */
  126. public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
  127. return ResponseSerializer { _, response, data, error in
  128. guard error == nil else { return .Failure(error!) }
  129. if let response = response where response.statusCode == 204 { return .Success(NSData()) }
  130. guard let validData = data else {
  131. let failureReason = "Data could not be serialized. Input data was nil."
  132. let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
  133. return .Failure(error)
  134. }
  135. return .Success(validData)
  136. }
  137. }
  138. /**
  139. Adds a handler to be called once the request has finished.
  140. - parameter completionHandler: The code to be executed once the request has finished.
  141. - returns: The request.
  142. */
  143. public func responseData(
  144. queue queue: dispatch_queue_t? = nil,
  145. completionHandler: Response<NSData, NSError> -> Void)
  146. -> Self
  147. {
  148. return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
  149. }
  150. }
  151. // MARK: - String
  152. extension Request {
  153. /**
  154. Creates a response serializer that returns a string initialized from the response data with the specified
  155. string encoding.
  156. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  157. response, falling back to the default HTTP default character set, ISO-8859-1.
  158. - returns: A string response serializer.
  159. */
  160. public static func stringResponseSerializer(
  161. encoding encoding: NSStringEncoding? = nil)
  162. -> ResponseSerializer<String, NSError>
  163. {
  164. return ResponseSerializer { _, response, data, error in
  165. guard error == nil else { return .Failure(error!) }
  166. if let response = response where response.statusCode == 204 { return .Success("") }
  167. guard let validData = data else {
  168. let failureReason = "String could not be serialized. Input data was nil."
  169. let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
  170. return .Failure(error)
  171. }
  172. var convertedEncoding = encoding
  173. if let encodingName = response?.textEncodingName where convertedEncoding == nil {
  174. convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
  175. CFStringConvertIANACharSetNameToEncoding(encodingName)
  176. )
  177. }
  178. let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
  179. if let string = String(data: validData, encoding: actualEncoding) {
  180. return .Success(string)
  181. } else {
  182. let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
  183. let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
  184. return .Failure(error)
  185. }
  186. }
  187. }
  188. /**
  189. Adds a handler to be called once the request has finished.
  190. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  191. server response, falling back to the default HTTP default character set,
  192. ISO-8859-1.
  193. - parameter completionHandler: A closure to be executed once the request has finished.
  194. - returns: The request.
  195. */
  196. public func responseString(
  197. queue queue: dispatch_queue_t? = nil,
  198. encoding: NSStringEncoding? = nil,
  199. completionHandler: Response<String, NSError> -> Void)
  200. -> Self
  201. {
  202. return response(
  203. queue: queue,
  204. responseSerializer: Request.stringResponseSerializer(encoding: encoding),
  205. completionHandler: completionHandler
  206. )
  207. }
  208. }
  209. // MARK: - JSON
  210. extension Request {
  211. /**
  212. Creates a response serializer that returns a JSON object constructed from the response data using
  213. `NSJSONSerialization` with the specified reading options.
  214. - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  215. - returns: A JSON object response serializer.
  216. */
  217. public static func JSONResponseSerializer(
  218. options options: NSJSONReadingOptions = .AllowFragments)
  219. -> ResponseSerializer<AnyObject, NSError>
  220. {
  221. return ResponseSerializer { _, response, data, error in
  222. guard error == nil else { return .Failure(error!) }
  223. if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
  224. guard let validData = data where validData.length > 0 else {
  225. let failureReason = "JSON could not be serialized. Input data was nil or zero length."
  226. let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
  227. return .Failure(error)
  228. }
  229. do {
  230. let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
  231. return .Success(JSON)
  232. } catch {
  233. return .Failure(error as NSError)
  234. }
  235. }
  236. }
  237. /**
  238. Adds a handler to be called once the request has finished.
  239. - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  240. - parameter completionHandler: A closure to be executed once the request has finished.
  241. - returns: The request.
  242. */
  243. public func responseJSON(
  244. queue queue: dispatch_queue_t? = nil,
  245. options: NSJSONReadingOptions = .AllowFragments,
  246. completionHandler: Response<AnyObject, NSError> -> Void)
  247. -> Self
  248. {
  249. return response(
  250. queue: queue,
  251. responseSerializer: Request.JSONResponseSerializer(options: options),
  252. completionHandler: completionHandler
  253. )
  254. }
  255. }
  256. // MARK: - Property List
  257. extension Request {
  258. /**
  259. Creates a response serializer that returns an object constructed from the response data using
  260. `NSPropertyListSerialization` with the specified reading options.
  261. - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
  262. - returns: A property list object response serializer.
  263. */
  264. public static func propertyListResponseSerializer(
  265. options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
  266. -> ResponseSerializer<AnyObject, NSError>
  267. {
  268. return ResponseSerializer { _, response, data, error in
  269. guard error == nil else { return .Failure(error!) }
  270. if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
  271. guard let validData = data where validData.length > 0 else {
  272. let failureReason = "Property list could not be serialized. Input data was nil or zero length."
  273. let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
  274. return .Failure(error)
  275. }
  276. do {
  277. let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
  278. return .Success(plist)
  279. } catch {
  280. return .Failure(error as NSError)
  281. }
  282. }
  283. }
  284. /**
  285. Adds a handler to be called once the request has finished.
  286. - parameter options: The property list reading options. `0` by default.
  287. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
  288. arguments: the URL request, the URL response, the server data and the result
  289. produced while creating the property list.
  290. - returns: The request.
  291. */
  292. public func responsePropertyList(
  293. queue queue: dispatch_queue_t? = nil,
  294. options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
  295. completionHandler: Response<AnyObject, NSError> -> Void)
  296. -> Self
  297. {
  298. return response(
  299. queue: queue,
  300. responseSerializer: Request.propertyListResponseSerializer(options: options),
  301. completionHandler: completionHandler
  302. )
  303. }
  304. }