ParameterEncoding.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. //
  2. // ParameterEncoding.swift
  3. //
  4. // Copyright (c) 2014-2016 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. /// HTTP method definitions.
  26. ///
  27. /// See https://tools.ietf.org/html/rfc7231#section-4.3
  28. public enum HTTPMethod: String {
  29. case options = "OPTIONS"
  30. case get = "GET"
  31. case head = "HEAD"
  32. case post = "POST"
  33. case put = "PUT"
  34. case patch = "PATCH"
  35. case delete = "DELETE"
  36. case trace = "TRACE"
  37. case connect = "CONNECT"
  38. }
  39. // MARK: -
  40. /// A dictionary of parameters to apply to a `URLRequest`.
  41. public typealias Parameters = [String: Any]
  42. /// A type used to define how a set of parameters are applied to a `URLRequest`.
  43. public protocol ParameterEncoding {
  44. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  45. ///
  46. /// - parameter urlRequest: The request to have parameters applied.
  47. /// - parameter parameters: The parameters to apply.
  48. ///
  49. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  50. ///
  51. /// - returns: The encoded request.
  52. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
  53. }
  54. // MARK: -
  55. /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
  56. /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
  57. /// the HTTP body depends on the destination of the encoding.
  58. ///
  59. /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
  60. /// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode
  61. /// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending
  62. /// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
  63. public struct URLEncoding: ParameterEncoding {
  64. // MARK: Helper Types
  65. /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
  66. /// resulting URL request.
  67. ///
  68. /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
  69. /// requests and sets as the HTTP body for requests with any other HTTP method.
  70. /// - queryString: Sets or appends encoded query string result to existing query string.
  71. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
  72. public enum Destination {
  73. case methodDependent, queryString, httpBody
  74. }
  75. // MARK: Properties
  76. /// Returns a default `URLEncoding` instance.
  77. public static var `default`: URLEncoding { return URLEncoding() }
  78. /// Returns a `URLEncoding` instance with a `.methodDependent` destination.
  79. public static var methodDependent: URLEncoding { return URLEncoding() }
  80. /// Returns a `URLEncoding` instance with a `.queryString` destination.
  81. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
  82. /// Returns a `URLEncoding` instance with an `.httpBody` destination.
  83. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
  84. /// The destination defining where the encoded query string is to be applied to the URL request.
  85. public let destination: Destination
  86. // MARK: Initialization
  87. /// Creates a `URLEncoding` instance using the specified destination.
  88. ///
  89. /// - parameter destination: The destination defining where the encoded query string is to be applied.
  90. ///
  91. /// - returns: The new `URLEncoding` instance.
  92. public init(destination: Destination = .methodDependent) {
  93. self.destination = destination
  94. }
  95. // MARK: Encoding
  96. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  97. ///
  98. /// - parameter urlRequest: The request to have parameters applied.
  99. /// - parameter parameters: The parameters to apply.
  100. ///
  101. /// - throws: An `Error` if the encoding process encounters an error.
  102. ///
  103. /// - returns: The encoded request.
  104. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  105. var urlRequest = try urlRequest.asURLRequest()
  106. guard let parameters = parameters else { return urlRequest }
  107. if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
  108. guard let url = urlRequest.url else {
  109. throw AFError.parameterEncodingFailed(reason: .missingURL)
  110. }
  111. if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
  112. let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
  113. urlComponents.percentEncodedQuery = percentEncodedQuery
  114. urlRequest.url = urlComponents.url
  115. }
  116. } else {
  117. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  118. urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
  119. }
  120. urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
  121. }
  122. return urlRequest
  123. }
  124. /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
  125. ///
  126. /// - parameter key: The key of the query component.
  127. /// - parameter value: The value of the query component.
  128. ///
  129. /// - returns: The percent-escaped, URL encoded query string components.
  130. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  131. var components: [(String, String)] = []
  132. if let dictionary = value as? [String: Any] {
  133. for (nestedKey, value) in dictionary {
  134. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  135. }
  136. } else if let array = value as? [Any] {
  137. for value in array {
  138. components += queryComponents(fromKey: "\(key)[]", value: value)
  139. }
  140. } else if let value = value as? NSNumber {
  141. if value.isBool {
  142. components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
  143. } else {
  144. components.append((escape(key), escape("\(value)")))
  145. }
  146. } else if let bool = value as? Bool {
  147. components.append((escape(key), escape((bool ? "1" : "0"))))
  148. } else {
  149. components.append((escape(key), escape("\(value)")))
  150. }
  151. return components
  152. }
  153. /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
  154. ///
  155. /// RFC 3986 states that the following characters are "reserved" characters.
  156. ///
  157. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  158. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  159. ///
  160. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  161. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  162. /// should be percent-escaped in the query string.
  163. ///
  164. /// - parameter string: The string to be percent-escaped.
  165. ///
  166. /// - returns: The percent-escaped string.
  167. public func escape(_ string: String) -> String {
  168. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  169. let subDelimitersToEncode = "!$&'()*+,;="
  170. var allowedCharacterSet = CharacterSet.urlQueryAllowed
  171. allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  172. return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
  173. }
  174. private func query(_ parameters: [String: Any]) -> String {
  175. var components: [(String, String)] = []
  176. for key in parameters.keys.sorted(by: <) {
  177. let value = parameters[key]!
  178. components += queryComponents(fromKey: key, value: value)
  179. }
  180. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  181. }
  182. private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  183. switch destination {
  184. case .queryString:
  185. return true
  186. case .httpBody:
  187. return false
  188. default:
  189. break
  190. }
  191. switch method {
  192. case .get, .head, .delete:
  193. return true
  194. default:
  195. return false
  196. }
  197. }
  198. }
  199. // MARK: -
  200. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  201. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  202. public struct JSONEncoding: ParameterEncoding {
  203. // MARK: Properties
  204. /// Returns a `JSONEncoding` instance with default writing options.
  205. public static var `default`: JSONEncoding { return JSONEncoding() }
  206. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  207. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
  208. /// The options for writing the parameters as JSON data.
  209. public let options: JSONSerialization.WritingOptions
  210. // MARK: Initialization
  211. /// Creates a `JSONEncoding` instance using the specified options.
  212. ///
  213. /// - parameter options: The options for writing the parameters as JSON data.
  214. ///
  215. /// - returns: The new `JSONEncoding` instance.
  216. public init(options: JSONSerialization.WritingOptions = []) {
  217. self.options = options
  218. }
  219. // MARK: Encoding
  220. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  221. ///
  222. /// - parameter urlRequest: The request to have parameters applied.
  223. /// - parameter parameters: The parameters to apply.
  224. ///
  225. /// - throws: An `Error` if the encoding process encounters an error.
  226. ///
  227. /// - returns: The encoded request.
  228. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  229. var urlRequest = try urlRequest.asURLRequest()
  230. guard let parameters = parameters else { return urlRequest }
  231. do {
  232. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  233. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  234. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  235. }
  236. urlRequest.httpBody = data
  237. } catch {
  238. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  239. }
  240. return urlRequest
  241. }
  242. }
  243. // MARK: -
  244. /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
  245. /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
  246. /// field of an encoded request is set to `application/x-plist`.
  247. public struct PropertyListEncoding: ParameterEncoding {
  248. // MARK: Properties
  249. /// Returns a default `PropertyListEncoding` instance.
  250. public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
  251. /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
  252. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
  253. /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
  254. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
  255. /// The property list serialization format.
  256. public let format: PropertyListSerialization.PropertyListFormat
  257. /// The options for writing the parameters as plist data.
  258. public let options: PropertyListSerialization.WriteOptions
  259. // MARK: Initialization
  260. /// Creates a `PropertyListEncoding` instance using the specified format and options.
  261. ///
  262. /// - parameter format: The property list serialization format.
  263. /// - parameter options: The options for writing the parameters as plist data.
  264. ///
  265. /// - returns: The new `PropertyListEncoding` instance.
  266. public init(
  267. format: PropertyListSerialization.PropertyListFormat = .xml,
  268. options: PropertyListSerialization.WriteOptions = 0)
  269. {
  270. self.format = format
  271. self.options = options
  272. }
  273. // MARK: Encoding
  274. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  275. ///
  276. /// - parameter urlRequest: The request to have parameters applied.
  277. /// - parameter parameters: The parameters to apply.
  278. ///
  279. /// - throws: An `Error` if the encoding process encounters an error.
  280. ///
  281. /// - returns: The encoded request.
  282. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  283. var urlRequest = try urlRequest.asURLRequest()
  284. guard let parameters = parameters else { return urlRequest }
  285. do {
  286. let data = try PropertyListSerialization.data(
  287. fromPropertyList: parameters,
  288. format: format,
  289. options: options
  290. )
  291. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  292. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  293. }
  294. urlRequest.httpBody = data
  295. } catch {
  296. throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
  297. }
  298. return urlRequest
  299. }
  300. }
  301. // MARK: -
  302. extension NSNumber {
  303. fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
  304. }