ResponseSerialization.swift 11 KB

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