ParameterEncoding.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. //
  2. // ParameterEncoding.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// A dictionary of parameters to apply to a `URLRequest`.
  26. public typealias Parameters = [String: Any]
  27. /// A type used to define how a set of parameters are applied to a `URLRequest`.
  28. public protocol ParameterEncoding {
  29. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  30. ///
  31. /// - parameter urlRequest: The request to have parameters applied.
  32. /// - parameter parameters: The parameters to apply.
  33. ///
  34. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  35. ///
  36. /// - returns: The encoded request.
  37. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
  38. }
  39. // MARK: -
  40. /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
  41. /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
  42. /// the HTTP body depends on the destination of the encoding.
  43. ///
  44. /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
  45. /// `application/x-www-form-urlencoded; charset=utf-8`.
  46. ///
  47. /// There is no published specification for how to encode collection types. By default the convention of appending
  48. /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
  49. /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
  50. /// square brackets appended to array keys.
  51. ///
  52. /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
  53. /// `true` as 1 and `false` as 0.
  54. public struct URLEncoding: ParameterEncoding {
  55. // MARK: Helper Types
  56. /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
  57. /// resulting URL request.
  58. ///
  59. /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
  60. /// requests and sets as the HTTP body for requests with any other HTTP method.
  61. /// - queryString: Sets or appends encoded query string result to existing query string.
  62. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
  63. public enum Destination {
  64. case methodDependent, queryString, httpBody
  65. func encodesParametersInURL(for method: HTTPMethod) -> Bool {
  66. switch self {
  67. case .methodDependent: return [.get, .head, .delete].contains(method)
  68. case .queryString: return true
  69. case .httpBody: return false
  70. }
  71. }
  72. }
  73. /// Configures how `Array` parameters are encoded.
  74. ///
  75. /// - brackets: An empty set of square brackets is appended to the key for every value.
  76. /// This is the default behavior.
  77. /// - noBrackets: No brackets are appended. The key is encoded as is.
  78. public enum ArrayEncoding {
  79. case brackets, noBrackets
  80. func encode(key: String) -> String {
  81. switch self {
  82. case .brackets:
  83. return "\(key)[]"
  84. case .noBrackets:
  85. return key
  86. }
  87. }
  88. }
  89. /// Configures how `Bool` parameters are encoded.
  90. ///
  91. /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior.
  92. /// - literal: Encode `true` and `false` as string literals.
  93. public enum BoolEncoding {
  94. case numeric, literal
  95. func encode(value: Bool) -> String {
  96. switch self {
  97. case .numeric:
  98. return value ? "1" : "0"
  99. case .literal:
  100. return value ? "true" : "false"
  101. }
  102. }
  103. }
  104. // MARK: Properties
  105. /// Returns a default `URLEncoding` instance with a `.methodDependent` destination.
  106. public static var `default`: URLEncoding { return URLEncoding() }
  107. /// Returns a `URLEncoding` instance with a `.queryString` destination.
  108. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
  109. /// Returns a `URLEncoding` instance with an `.httpBody` destination.
  110. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
  111. /// The destination defining where the encoded query string is to be applied to the URL request.
  112. public let destination: Destination
  113. /// The encoding to use for `Array` parameters.
  114. public let arrayEncoding: ArrayEncoding
  115. /// The encoding to use for `Bool` parameters.
  116. public let boolEncoding: BoolEncoding
  117. // MARK: Initialization
  118. /// Creates a `URLEncoding` instance using the specified destination.
  119. ///
  120. /// - parameter destination: The destination defining where the encoded query string is to be applied.
  121. /// - parameter arrayEncoding: The encoding to use for `Array` parameters.
  122. /// - parameter boolEncoding: The encoding to use for `Bool` parameters.
  123. ///
  124. /// - returns: The new `URLEncoding` instance.
  125. public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) {
  126. self.destination = destination
  127. self.arrayEncoding = arrayEncoding
  128. self.boolEncoding = boolEncoding
  129. }
  130. // MARK: Encoding
  131. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  132. ///
  133. /// - parameter urlRequest: The request to have parameters applied.
  134. /// - parameter parameters: The parameters to apply.
  135. ///
  136. /// - throws: An `Error` if the encoding process encounters an error.
  137. ///
  138. /// - returns: The encoded request.
  139. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  140. var urlRequest = try urlRequest.asURLRequest()
  141. guard let parameters = parameters else { return urlRequest }
  142. if let method = urlRequest.method, destination.encodesParametersInURL(for: method) {
  143. guard let url = urlRequest.url else {
  144. throw AFError.parameterEncodingFailed(reason: .missingURL)
  145. }
  146. if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
  147. let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
  148. urlComponents.percentEncodedQuery = percentEncodedQuery
  149. urlRequest.url = urlComponents.url
  150. }
  151. } else {
  152. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  153. urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
  154. }
  155. urlRequest.httpBody = Data(query(parameters).utf8)
  156. }
  157. return urlRequest
  158. }
  159. /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
  160. ///
  161. /// - parameter key: The key of the query component.
  162. /// - parameter value: The value of the query component.
  163. ///
  164. /// - returns: The percent-escaped, URL encoded query string components.
  165. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  166. var components: [(String, String)] = []
  167. if let dictionary = value as? [String: Any] {
  168. for (nestedKey, value) in dictionary {
  169. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  170. }
  171. } else if let array = value as? [Any] {
  172. for value in array {
  173. components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
  174. }
  175. } else if let value = value as? NSNumber {
  176. if value.isBool {
  177. components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue))))
  178. } else {
  179. components.append((escape(key), escape("\(value)")))
  180. }
  181. } else if let bool = value as? Bool {
  182. components.append((escape(key), escape(boolEncoding.encode(value: bool))))
  183. } else {
  184. components.append((escape(key), escape("\(value)")))
  185. }
  186. return components
  187. }
  188. /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
  189. ///
  190. /// - parameter string: The string to be percent-escaped.
  191. ///
  192. /// - returns: The percent-escaped string.
  193. public func escape(_ string: String) -> String {
  194. return string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
  195. }
  196. private func query(_ parameters: [String: Any]) -> String {
  197. var components: [(String, String)] = []
  198. for key in parameters.keys.sorted(by: <) {
  199. let value = parameters[key]!
  200. components += queryComponents(fromKey: key, value: value)
  201. }
  202. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  203. }
  204. }
  205. // MARK: -
  206. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  207. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  208. public struct JSONEncoding: ParameterEncoding {
  209. // MARK: Properties
  210. /// Returns a `JSONEncoding` instance with default writing options.
  211. public static var `default`: JSONEncoding { return JSONEncoding() }
  212. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  213. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
  214. /// The options for writing the parameters as JSON data.
  215. public let options: JSONSerialization.WritingOptions
  216. // MARK: Initialization
  217. /// Creates a `JSONEncoding` instance using the specified options.
  218. ///
  219. /// - parameter options: The options for writing the parameters as JSON data.
  220. ///
  221. /// - returns: The new `JSONEncoding` instance.
  222. public init(options: JSONSerialization.WritingOptions = []) {
  223. self.options = options
  224. }
  225. // MARK: Encoding
  226. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  227. ///
  228. /// - parameter urlRequest: The request to have parameters applied.
  229. /// - parameter parameters: The parameters to apply.
  230. ///
  231. /// - throws: An `Error` if the encoding process encounters an error.
  232. ///
  233. /// - returns: The encoded request.
  234. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  235. var urlRequest = try urlRequest.asURLRequest()
  236. guard let parameters = parameters else { return urlRequest }
  237. do {
  238. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  239. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  240. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  241. }
  242. urlRequest.httpBody = data
  243. } catch {
  244. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  245. }
  246. return urlRequest
  247. }
  248. /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
  249. ///
  250. /// - parameter urlRequest: The request to apply the JSON object to.
  251. /// - parameter jsonObject: The JSON object to apply to the request.
  252. ///
  253. /// - throws: An `Error` if the encoding process encounters an error.
  254. ///
  255. /// - returns: The encoded request.
  256. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
  257. var urlRequest = try urlRequest.asURLRequest()
  258. guard let jsonObject = jsonObject else { return urlRequest }
  259. do {
  260. let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
  261. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  262. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  263. }
  264. urlRequest.httpBody = data
  265. } catch {
  266. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  267. }
  268. return urlRequest
  269. }
  270. }
  271. // MARK: -
  272. extension NSNumber {
  273. fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
  274. }