ParameterEncoding.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //
  2. // ParameterEncoding.swift
  3. //
  4. // Copyright (c) 2014-2017 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. var escaped = ""
  173. //==========================================================================================================
  174. //
  175. // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
  176. // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
  177. // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
  178. // info, please refer to:
  179. //
  180. // - https://github.com/Alamofire/Alamofire/issues/206
  181. //
  182. //==========================================================================================================
  183. if #available(iOS 8.3, *) {
  184. escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
  185. } else {
  186. let batchSize = 50
  187. var index = string.startIndex
  188. while index != string.endIndex {
  189. let startIndex = index
  190. let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
  191. let range = startIndex..<endIndex
  192. let substring = string[range]
  193. escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring)
  194. index = endIndex
  195. }
  196. }
  197. return escaped
  198. }
  199. private func query(_ parameters: [String: Any]) -> String {
  200. var components: [(String, String)] = []
  201. for key in parameters.keys.sorted(by: <) {
  202. let value = parameters[key]!
  203. components += queryComponents(fromKey: key, value: value)
  204. }
  205. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  206. }
  207. private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  208. switch destination {
  209. case .queryString:
  210. return true
  211. case .httpBody:
  212. return false
  213. default:
  214. break
  215. }
  216. switch method {
  217. case .get, .head, .delete:
  218. return true
  219. default:
  220. return false
  221. }
  222. }
  223. }
  224. // MARK: -
  225. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  226. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  227. public struct JSONEncoding: ParameterEncoding {
  228. // MARK: Properties
  229. /// Returns a `JSONEncoding` instance with default writing options.
  230. public static var `default`: JSONEncoding { return JSONEncoding() }
  231. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  232. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
  233. /// The options for writing the parameters as JSON data.
  234. public let options: JSONSerialization.WritingOptions
  235. // MARK: Initialization
  236. /// Creates a `JSONEncoding` instance using the specified options.
  237. ///
  238. /// - parameter options: The options for writing the parameters as JSON data.
  239. ///
  240. /// - returns: The new `JSONEncoding` instance.
  241. public init(options: JSONSerialization.WritingOptions = []) {
  242. self.options = options
  243. }
  244. // MARK: Encoding
  245. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  246. ///
  247. /// - parameter urlRequest: The request to have parameters applied.
  248. /// - parameter parameters: The parameters to apply.
  249. ///
  250. /// - throws: An `Error` if the encoding process encounters an error.
  251. ///
  252. /// - returns: The encoded request.
  253. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  254. var urlRequest = try urlRequest.asURLRequest()
  255. guard let parameters = parameters else { return urlRequest }
  256. do {
  257. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  258. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  259. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  260. }
  261. urlRequest.httpBody = data
  262. } catch {
  263. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  264. }
  265. return urlRequest
  266. }
  267. /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
  268. ///
  269. /// - parameter urlRequest: The request to apply the JSON object to.
  270. /// - parameter jsonObject: The JSON object to apply to the request.
  271. ///
  272. /// - throws: An `Error` if the encoding process encounters an error.
  273. ///
  274. /// - returns: The encoded request.
  275. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
  276. var urlRequest = try urlRequest.asURLRequest()
  277. guard let jsonObject = jsonObject else { return urlRequest }
  278. do {
  279. let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
  280. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  281. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  282. }
  283. urlRequest.httpBody = data
  284. } catch {
  285. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  286. }
  287. return urlRequest
  288. }
  289. }
  290. // MARK: -
  291. /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
  292. /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
  293. /// field of an encoded request is set to `application/x-plist`.
  294. public struct PropertyListEncoding: ParameterEncoding {
  295. // MARK: Properties
  296. /// Returns a default `PropertyListEncoding` instance.
  297. public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
  298. /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
  299. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
  300. /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
  301. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
  302. /// The property list serialization format.
  303. public let format: PropertyListSerialization.PropertyListFormat
  304. /// The options for writing the parameters as plist data.
  305. public let options: PropertyListSerialization.WriteOptions
  306. // MARK: Initialization
  307. /// Creates a `PropertyListEncoding` instance using the specified format and options.
  308. ///
  309. /// - parameter format: The property list serialization format.
  310. /// - parameter options: The options for writing the parameters as plist data.
  311. ///
  312. /// - returns: The new `PropertyListEncoding` instance.
  313. public init(
  314. format: PropertyListSerialization.PropertyListFormat = .xml,
  315. options: PropertyListSerialization.WriteOptions = 0)
  316. {
  317. self.format = format
  318. self.options = options
  319. }
  320. // MARK: Encoding
  321. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  322. ///
  323. /// - parameter urlRequest: The request to have parameters applied.
  324. /// - parameter parameters: The parameters to apply.
  325. ///
  326. /// - throws: An `Error` if the encoding process encounters an error.
  327. ///
  328. /// - returns: The encoded request.
  329. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  330. var urlRequest = try urlRequest.asURLRequest()
  331. guard let parameters = parameters else { return urlRequest }
  332. do {
  333. let data = try PropertyListSerialization.data(
  334. fromPropertyList: parameters,
  335. format: format,
  336. options: options
  337. )
  338. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  339. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  340. }
  341. urlRequest.httpBody = data
  342. } catch {
  343. throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
  344. }
  345. return urlRequest
  346. }
  347. }
  348. // MARK: -
  349. extension NSNumber {
  350. fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
  351. }