ParameterEncoding.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // ParameterEncoding.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. /**
  24. HTTP method definitions.
  25. See https://tools.ietf.org/html/rfc7231#section-4.3
  26. */
  27. public enum Method: String {
  28. case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
  29. }
  30. // MARK: - ParameterEncoding
  31. /**
  32. Used to specify the way in which a set of parameters are applied to a URL request.
  33. - URL: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE`
  34. requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header
  35. field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since
  36. there is no published specification for how to encode collection types, the convention of appending
  37. `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square
  38. brackets for nested dictionary values (`foo[bar]=baz`).
  39. - JSON: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as
  40. the body of the request. The `Content-Type` HTTP header field of an encoded request is set to
  41. `application/json`.
  42. - PropertyList: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
  43. according to the associated format and write options values, which is set as the body of the
  44. request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
  45. - Custom: Uses the associated closure value to construct a new request given an existing request and
  46. parameters.
  47. */
  48. public enum ParameterEncoding {
  49. case URL
  50. case JSON
  51. case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
  52. case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
  53. /**
  54. Creates a URL request by encoding parameters and applying them onto an existing request.
  55. - parameter URLRequest: The request to have parameters applied
  56. - parameter parameters: The parameters to apply
  57. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
  58. if any.
  59. */
  60. public func encode(
  61. URLRequest: URLRequestConvertible,
  62. parameters: [String: AnyObject]?)
  63. -> (NSMutableURLRequest, NSError?)
  64. {
  65. var mutableURLRequest = URLRequest.URLRequest
  66. if parameters == nil {
  67. return (mutableURLRequest, nil)
  68. }
  69. var encodingError: NSError? = nil
  70. switch self {
  71. case .URL:
  72. func query(parameters: [String: AnyObject]) -> String {
  73. var components: [(String, String)] = []
  74. for key in Array(parameters.keys).sort(<) {
  75. let value: AnyObject! = parameters[key]
  76. components += queryComponents(key, value)
  77. }
  78. return "&".join(components.map { "\($0)=\($1)" } as [String])
  79. }
  80. func encodesParametersInURL(method: Method) -> Bool {
  81. switch method {
  82. case .GET, .HEAD, .DELETE:
  83. return true
  84. default:
  85. return false
  86. }
  87. }
  88. if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
  89. if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
  90. let percentEncodedQuery = (
  91. (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters!)
  92. )
  93. URLComponents.percentEncodedQuery = percentEncodedQuery
  94. mutableURLRequest.URL = URLComponents.URL
  95. }
  96. } else {
  97. if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
  98. mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  99. }
  100. mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(
  101. NSUTF8StringEncoding,
  102. allowLossyConversion: false
  103. )
  104. }
  105. case .JSON:
  106. do {
  107. let options = NSJSONWritingOptions()
  108. let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)
  109. mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  110. mutableURLRequest.HTTPBody = data
  111. } catch {
  112. encodingError = error as NSError
  113. }
  114. case .PropertyList(let format, let options):
  115. do {
  116. let data = try NSPropertyListSerialization.dataWithPropertyList(
  117. parameters!,
  118. format: format,
  119. options: options
  120. )
  121. mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  122. mutableURLRequest.HTTPBody = data
  123. } catch {
  124. encodingError = error as NSError
  125. }
  126. case .Custom(let closure):
  127. (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
  128. }
  129. return (mutableURLRequest, encodingError)
  130. }
  131. func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
  132. var components: [(String, String)] = []
  133. if let dictionary = value as? [String: AnyObject] {
  134. for (nestedKey, value) in dictionary {
  135. components += queryComponents("\(key)[\(nestedKey)]", value)
  136. }
  137. } else if let array = value as? [AnyObject] {
  138. for value in array {
  139. components += queryComponents("\(key)[]", value)
  140. }
  141. } else {
  142. components.append((escape(key), escape("\(value)")))
  143. }
  144. return components
  145. }
  146. /**
  147. Returns a percent escaped string following RFC 3986 for a query string key or value.
  148. RFC 3986 states that the following characters are "reserved" characters.
  149. - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  150. - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  151. In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  152. query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  153. should be percent escaped in the query string.
  154. - parameter string: The string to be percent escaped.
  155. - returns: The percent escaped string.
  156. */
  157. func escape(string: String) -> String {
  158. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  159. let subDelimitersToEncode = "!$&'()*+,;="
  160. let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
  161. allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
  162. return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? ""
  163. }
  164. }