ResponseSerialization.swift 13 KB

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