美文网首页
ParameterEncoding

ParameterEncoding

作者: 幸运的小强本人 | 来源:发表于2016-02-29 11:52 被阅读445次

/**
HTTP method definitions.
*/

public enum Method: String {
  case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}

// MARK: ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.

-URL: Creates a query string to be set as or
appended ti abt 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; charset=utf-8',
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').
...
*/

public enum ParameterEncoding {
    case URL
    case URLEncodedInURL
    case JSON
    case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
    case Custom((URLRequestConvertible, [String: AnyObject]?)->(NSMutableURLRequest, NSError?))

    /**
        Creates a URL request by encoding 
        parameters and applying them onto an 
        existing request

        - parameter URLRequest: The request to 
          have parameters applied.
        - parameter parameters: The parameters to apply.

        - returns: A tuple containing the 
              constructed request and the error that 
              occurred during parameter encoding if any.
    */

    public func encode(URLRequest: URLRequestConvertible, parameter: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) {
      var mutableURLRequest = URLRequest.URLRequest
      guard let parameters = parameters else {
        return (mutableURLRequest, nil)
      }

      var encodingError: NSError? = nil
  
      switch self {
        case .URL, .URLEncodedInURL:
            func query(parameters: [String: AnyObject]) ->String {
                var components: [(String, String)] = []

                for key in parameters.keys.sort(<) {
                    let value = parameters[key]!
                    components += queryComponents(key, value)
                }

                return (components.map { "($0)=\($1)" } as [String]).joinWithSeparator("&")
            }

            func encodesParametersInURL(method: Method) -> Bool {
                switch self {
                    case .URLEncodedInURL:
                        return true
                    default:
                        break
                }

                switch method {
                    case .GET, .HEAD, .DELETE:
                        return true
                    default:
                        return false
                }
            }

            if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
                if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) where !parameters.isEmpty {
                    let percentEncodedQuery = (URLComponents.percentEncodedQuery.map {
                        $0 + "&" } ?? "") + query(parameters) 
                     URLComponents.percentEncodedQuery = percentEncodedQuery            
                      mutableURLRequest.URL = URLComponents.URL
                    }
                }
            }else {
                if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
                    mutableURLRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
                }

                mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            }

        case .JSON:
            do {
                let options = NSJSONWriteOptions()
                let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)

                mutableURLRequest.setValue("application/json", forHTTPHeaderField:"Content-Type")
                mutableURLRequest.HTTPBody = data
            } catch {
                encodingError = error as NSError
            }

        case .PropertyList(let format, let options):
            do {
                let data = try NSPropertyListSerialization.dataWithPropertyList(parameters, format: format, options: options)

                mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField:"Content-Type")
                mutableURLRequest.HTTPBody = data
            } catch {
                encodingError = error as NSError
            }

        case .Custom(let closure):
            (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
        }

        return (mutableURLRequest, encodingError)
    }

    /**
        Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
    */
    public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
        var components: [(String, String)] = []

        if let dictionary = value as? [String: AnyObject] {
            for (nestedKey, value) in dictionary {
                components += queryComponents("\(key)[\(nestedKey)]", value)
            }
        }else if let array = value as? [AnyObject] {
            for value in array {
                components += queryComponents("\(key)[]", value)
            }
        }else {
            components.append((escape(key), escape("\(value)")))
        }

        return components
    }

    /**
        Returns a percent-escaped string following RFC 3986 for a query string key or value.
    */
    public func escape(string: String) -> String {
        ...
  
        return ""
    }
}

相关文章

网友评论

      本文标题:ParameterEncoding

      本文链接:https://www.haomeiwen.com/subject/ibdgkttx.html