ParameterEncoding.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // Alamofire.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 http://tools.ietf.org/html/rfc7231#section-4.3
  26. */
  27. public enum Method: String {
  28. case OPTIONS = "OPTIONS"
  29. case GET = "GET"
  30. case HEAD = "HEAD"
  31. case POST = "POST"
  32. case PUT = "PUT"
  33. case PATCH = "PATCH"
  34. case DELETE = "DELETE"
  35. case TRACE = "TRACE"
  36. case CONNECT = "CONNECT"
  37. }
  38. // MARK: - ParameterEncoding
  39. /**
  40. Used to specify the way in which a set of parameters are applied to a URL request.
  41. */
  42. public enum ParameterEncoding {
  43. /**
  44. A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
  45. */
  46. case URL
  47. /**
  48. Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  49. */
  50. case JSON
  51. /**
  52. Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
  53. */
  54. case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
  55. /**
  56. Uses the associated closure value to construct a new request given an existing request and parameters.
  57. */
  58. case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
  59. /**
  60. Creates a URL request by encoding parameters and applying them onto an existing request.
  61. :param: URLRequest The request to have parameters applied
  62. :param: parameters The parameters to apply
  63. :returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
  64. */
  65. public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
  66. if parameters == nil {
  67. return (URLRequest.URLRequest, nil)
  68. }
  69. var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
  70. var error: NSError? = nil
  71. switch self {
  72. case .URL:
  73. func query(parameters: [String: AnyObject]) -> String {
  74. var components: [(String, String)] = []
  75. for key in sorted(Array(parameters.keys), <) {
  76. let value: AnyObject! = parameters[key]
  77. components += self.queryComponents(key, value)
  78. }
  79. return join("&", components.map{"\($0)=\($1)"} as [String])
  80. }
  81. func encodesParametersInURL(method: Method) -> Bool {
  82. switch method {
  83. case .GET, .HEAD, .DELETE:
  84. return true
  85. default:
  86. return false
  87. }
  88. }
  89. let method = Method(rawValue: mutableURLRequest.HTTPMethod)
  90. if method != nil && encodesParametersInURL(method!) {
  91. if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
  92. URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
  93. mutableURLRequest.URL = URLComponents.URL
  94. }
  95. } else {
  96. if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
  97. mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  98. }
  99. mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  100. }
  101. case .JSON:
  102. let options = NSJSONWritingOptions.allZeros
  103. if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
  104. mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  105. mutableURLRequest.HTTPBody = data
  106. }
  107. case .PropertyList(let (format, options)):
  108. if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
  109. mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  110. mutableURLRequest.HTTPBody = data
  111. }
  112. case .Custom(let closure):
  113. return closure(mutableURLRequest, parameters)
  114. }
  115. return (mutableURLRequest, error)
  116. }
  117. func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
  118. var components: [(String, String)] = []
  119. if let dictionary = value as? [String: AnyObject] {
  120. for (nestedKey, value) in dictionary {
  121. components += queryComponents("\(key)[\(nestedKey)]", value)
  122. }
  123. } else if let array = value as? [AnyObject] {
  124. for value in array {
  125. components += queryComponents("\(key)[]", value)
  126. }
  127. } else {
  128. components.extend([(escape(key), escape("\(value)"))])
  129. }
  130. return components
  131. }
  132. func escape(string: String) -> String {
  133. let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
  134. return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
  135. }
  136. }