ResponseSerialization.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // ResponseSerialization.swift
  2. //
  3. // Copyright (c) 2014–2015 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 ResponseSerializer {
  28. /// The type of serialized object to be created by this `ResponseSerializer`.
  29. typealias SerializedObject
  30. /**
  31. A closure used by response handlers that takes a request, response, and data and returns a serialized object and
  32. any error that occured in the process.
  33. */
  34. var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
  35. }
  36. /**
  37. A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
  38. */
  39. public struct GenericResponseSerializer<T>: ResponseSerializer {
  40. /// The type of serialized object to be created by this `ResponseSerializer`.
  41. public typealias SerializedObject = T
  42. /**
  43. A closure used by response handlers that takes a request, response, and data and returns a serialized object and
  44. any error that occured in the process.
  45. */
  46. public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
  47. /**
  48. Initializes the `GenericResponseSerializer` instance with the given serialize response closure.
  49. - parameter serializeResponse: The closure used to serialize the response.
  50. - returns: The new generic response serializer instance.
  51. */
  52. public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)) {
  53. self.serializeResponse = serializeResponse
  54. }
  55. }
  56. // MARK: - Default
  57. extension Request {
  58. /**
  59. Adds a handler to be called once the request has finished.
  60. - parameter queue: The queue on which the completion handler is dispatched.
  61. - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  62. and data.
  63. - parameter completionHandler: The code to be executed once the request has finished.
  64. - returns: The request.
  65. */
  66. public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
  67. queue: dispatch_queue_t? = nil,
  68. responseSerializer: T,
  69. completionHandler: (NSURLRequest?, NSHTTPURLResponse?, V?, NSError?) -> Void)
  70. -> Self
  71. {
  72. delegate.queue.addOperationWithBlock {
  73. let result: V?
  74. let error: NSError?
  75. (result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
  76. dispatch_async(queue ?? dispatch_get_main_queue()) {
  77. completionHandler(self.request, self.response, result, self.delegate.error ?? error)
  78. }
  79. }
  80. return self
  81. }
  82. }
  83. // MARK: - Data
  84. extension Request {
  85. /**
  86. Creates a response serializer that returns the associated data as-is.
  87. - returns: A data response serializer.
  88. */
  89. public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
  90. return GenericResponseSerializer { request, response, data in
  91. return (data, nil)
  92. }
  93. }
  94. /**
  95. Adds a handler to be called once the request has finished.
  96. - parameter completionHandler: The code to be executed once the request has finished.
  97. - returns: The request.
  98. */
  99. public func response(completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
  100. return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
  101. }
  102. }
  103. // MARK: - String
  104. extension Request {
  105. /**
  106. Creates a response serializer that returns a string initialized from the response data with the specified
  107. string encoding.
  108. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  109. response, falling back to the default HTTP default character set, ISO-8859-1.
  110. - returns: A string response serializer.
  111. */
  112. public static func stringResponseSerializer(
  113. var encoding encoding: NSStringEncoding? = nil)
  114. -> GenericResponseSerializer<String>
  115. {
  116. return GenericResponseSerializer { _, response, data in
  117. guard let data = data where data.length > 0 else {
  118. return (nil, nil)
  119. }
  120. if let encodingName = response?.textEncodingName where encoding == nil {
  121. encoding = CFStringConvertEncodingToNSStringEncoding(
  122. CFStringConvertIANACharSetNameToEncoding(encodingName)
  123. )
  124. }
  125. let string = NSString(data: data, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
  126. return (string, nil)
  127. }
  128. }
  129. /**
  130. Adds a handler to be called once the request has finished.
  131. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  132. server response, falling back to the default HTTP default character set,
  133. ISO-8859-1.
  134. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4
  135. arguments: the URL request, the URL response, if one was received, the string,
  136. if one could be created from the URL response and data, and any error produced
  137. while creating the string.
  138. - returns: The request.
  139. */
  140. public func responseString(
  141. encoding encoding: NSStringEncoding? = nil,
  142. completionHandler: (NSURLRequest?, NSHTTPURLResponse?, String?, NSError?) -> Void)
  143. -> Self
  144. {
  145. return response(
  146. responseSerializer: Request.stringResponseSerializer(encoding: encoding),
  147. completionHandler: completionHandler
  148. )
  149. }
  150. }
  151. // MARK: - JSON
  152. extension Request {
  153. /**
  154. Creates a response serializer that returns a JSON object constructed from the response data using
  155. `NSJSONSerialization` with the specified reading options.
  156. - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  157. - returns: A JSON object response serializer.
  158. */
  159. public static func JSONResponseSerializer(
  160. options options: NSJSONReadingOptions = .AllowFragments)
  161. -> GenericResponseSerializer<AnyObject>
  162. {
  163. return GenericResponseSerializer { request, response, data in
  164. guard let data = data where data.length > 0 else {
  165. return (nil, nil)
  166. }
  167. var JSON: AnyObject?
  168. var serializationError: NSError?
  169. do {
  170. JSON = try NSJSONSerialization.JSONObjectWithData(data, options: options)
  171. } catch {
  172. serializationError = error as NSError
  173. }
  174. return (JSON, serializationError)
  175. }
  176. }
  177. /**
  178. Adds a handler to be called once the request has finished.
  179. - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
  180. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4
  181. arguments: the URL request, the URL response, if one was received, the JSON
  182. object, if one could be created from the URL response and data, and any error
  183. produced while creating the JSON object.
  184. - returns: The request.
  185. */
  186. public func responseJSON(
  187. options options: NSJSONReadingOptions = .AllowFragments,
  188. completionHandler: (NSURLRequest?, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
  189. -> Self
  190. {
  191. return response(
  192. responseSerializer: Request.JSONResponseSerializer(options: options),
  193. completionHandler: completionHandler
  194. )
  195. }
  196. }
  197. // MARK: - Property List
  198. extension Request {
  199. /**
  200. Creates a response serializer that returns an object constructed from the response data using
  201. `NSPropertyListSerialization` with the specified reading options.
  202. - parameter options: The property list reading options. `0` by default.
  203. - returns: A property list object response serializer.
  204. */
  205. public static func propertyListResponseSerializer(
  206. options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
  207. -> GenericResponseSerializer<AnyObject>
  208. {
  209. return GenericResponseSerializer { request, response, data in
  210. guard let data = data where data.length > 0 else {
  211. return (nil, nil)
  212. }
  213. var plist: AnyObject?
  214. var propertyListSerializationError: NSError?
  215. do {
  216. plist = try NSPropertyListSerialization.propertyListWithData(data, options: options, format: nil)
  217. } catch {
  218. propertyListSerializationError = error as NSError
  219. }
  220. return (plist, propertyListSerializationError)
  221. }
  222. }
  223. /**
  224. Adds a handler to be called once the request has finished.
  225. - parameter options: The property list reading options. `0` by default.
  226. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4
  227. arguments: the URL request, the URL response, if one was received, the property
  228. list, if one could be created from the URL response and data, and any error
  229. produced while creating the property list.
  230. - returns: The request.
  231. */
  232. public func responsePropertyList(
  233. options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
  234. completionHandler: (NSURLRequest?, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
  235. -> Self
  236. {
  237. return response(
  238. responseSerializer: Request.propertyListResponseSerializer(options: options),
  239. completionHandler: completionHandler
  240. )
  241. }
  242. }