ResponseSerialization.swift 13 KB

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