ResponseSerialization.swift 13 KB

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