ResponseSerialization.swift 13 KB

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