ParameterEncoding.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. 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.substring(with: range)
  193. escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? 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. #if swift(>=4.0)
  206. return components.map { "\($0.0)=\($0.1)" }.joined(separator: "&")
  207. #else
  208. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  209. #endif
  210. }
  211. private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  212. switch destination {
  213. case .queryString:
  214. return true
  215. case .httpBody:
  216. return false
  217. default:
  218. break
  219. }
  220. switch method {
  221. case .get, .head, .delete:
  222. return true
  223. default:
  224. return false
  225. }
  226. }
  227. }
  228. // MARK: -
  229. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  230. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json; charset=utf-8`.
  231. public struct JSONEncoding: ParameterEncoding {
  232. // MARK: Properties
  233. /// Returns a `JSONEncoding` instance with default writing options.
  234. public static var `default`: JSONEncoding { return JSONEncoding() }
  235. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  236. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
  237. /// The options for writing the parameters as JSON data.
  238. public let options: JSONSerialization.WritingOptions
  239. // MARK: Initialization
  240. /// Creates a `JSONEncoding` instance using the specified options.
  241. ///
  242. /// - parameter options: The options for writing the parameters as JSON data.
  243. ///
  244. /// - returns: The new `JSONEncoding` instance.
  245. public init(options: JSONSerialization.WritingOptions = []) {
  246. self.options = options
  247. }
  248. // MARK: Encoding
  249. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  250. ///
  251. /// - parameter urlRequest: The request to have parameters applied.
  252. /// - parameter parameters: The parameters to apply.
  253. ///
  254. /// - throws: An `Error` if the encoding process encounters an error.
  255. ///
  256. /// - returns: The encoded request.
  257. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  258. var urlRequest = try urlRequest.asURLRequest()
  259. guard let parameters = parameters else { return urlRequest }
  260. do {
  261. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  262. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  263. urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
  264. }
  265. urlRequest.httpBody = data
  266. } catch {
  267. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  268. }
  269. return urlRequest
  270. }
  271. /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
  272. ///
  273. /// - parameter urlRequest: The request to apply the JSON object to.
  274. /// - parameter jsonObject: The JSON object to apply to the request.
  275. ///
  276. /// - throws: An `Error` if the encoding process encounters an error.
  277. ///
  278. /// - returns: The encoded request.
  279. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
  280. var urlRequest = try urlRequest.asURLRequest()
  281. guard let jsonObject = jsonObject else { return urlRequest }
  282. do {
  283. let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
  284. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  285. urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
  286. }
  287. urlRequest.httpBody = data
  288. } catch {
  289. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  290. }
  291. return urlRequest
  292. }
  293. }
  294. // MARK: -
  295. /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
  296. /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
  297. /// field of an encoded request is set to `application/x-plist`.
  298. public struct PropertyListEncoding: ParameterEncoding {
  299. // MARK: Properties
  300. /// Returns a default `PropertyListEncoding` instance.
  301. public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
  302. /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
  303. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
  304. /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
  305. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
  306. /// The property list serialization format.
  307. public let format: PropertyListSerialization.PropertyListFormat
  308. /// The options for writing the parameters as plist data.
  309. public let options: PropertyListSerialization.WriteOptions
  310. // MARK: Initialization
  311. /// Creates a `PropertyListEncoding` instance using the specified format and options.
  312. ///
  313. /// - parameter format: The property list serialization format.
  314. /// - parameter options: The options for writing the parameters as plist data.
  315. ///
  316. /// - returns: The new `PropertyListEncoding` instance.
  317. public init(
  318. format: PropertyListSerialization.PropertyListFormat = .xml,
  319. options: PropertyListSerialization.WriteOptions = 0)
  320. {
  321. self.format = format
  322. self.options = options
  323. }
  324. // MARK: Encoding
  325. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  326. ///
  327. /// - parameter urlRequest: The request to have parameters applied.
  328. /// - parameter parameters: The parameters to apply.
  329. ///
  330. /// - throws: An `Error` if the encoding process encounters an error.
  331. ///
  332. /// - returns: The encoded request.
  333. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  334. var urlRequest = try urlRequest.asURLRequest()
  335. guard let parameters = parameters else { return urlRequest }
  336. do {
  337. let data = try PropertyListSerialization.data(
  338. fromPropertyList: parameters,
  339. format: format,
  340. options: options
  341. )
  342. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  343. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  344. }
  345. urlRequest.httpBody = data
  346. } catch {
  347. throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
  348. }
  349. return urlRequest
  350. }
  351. }
  352. // MARK: -
  353. extension NSNumber {
  354. fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
  355. }