ResponseSerialization.swift 13 KB

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