123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317 |
- import Foundation
- public typealias Parameters = [String: Any]
- public protocol ParameterEncoding {
-
-
-
-
-
-
-
-
- func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
- }
- public struct URLEncoding: ParameterEncoding {
-
-
-
- public enum Destination {
-
-
- case methodDependent
-
- case queryString
-
- case httpBody
- func encodesParametersInURL(for method: HTTPMethod) -> Bool {
- switch self {
- case .methodDependent: return [.get, .head, .delete].contains(method)
- case .queryString: return true
- case .httpBody: return false
- }
- }
- }
-
- public enum ArrayEncoding {
-
- case brackets
-
- case noBrackets
- func encode(key: String) -> String {
- switch self {
- case .brackets:
- return "\(key)[]"
- case .noBrackets:
- return key
- }
- }
- }
-
- public enum BoolEncoding {
-
- case numeric
-
- case literal
- func encode(value: Bool) -> String {
- switch self {
- case .numeric:
- return value ? "1" : "0"
- case .literal:
- return value ? "true" : "false"
- }
- }
- }
-
-
- public static var `default`: URLEncoding { URLEncoding() }
-
- public static var queryString: URLEncoding { URLEncoding(destination: .queryString) }
-
- public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) }
-
- public let destination: Destination
-
- public let arrayEncoding: ArrayEncoding
-
- public let boolEncoding: BoolEncoding
-
-
-
-
-
-
-
-
- public init(destination: Destination = .methodDependent,
- arrayEncoding: ArrayEncoding = .brackets,
- boolEncoding: BoolEncoding = .numeric) {
- self.destination = destination
- self.arrayEncoding = arrayEncoding
- self.boolEncoding = boolEncoding
- }
-
- public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
- var urlRequest = try urlRequest.asURLRequest()
- guard let parameters = parameters else { return urlRequest }
- if let method = urlRequest.method, destination.encodesParametersInURL(for: method) {
- guard let url = urlRequest.url else {
- throw AFError.parameterEncodingFailed(reason: .missingURL)
- }
- if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
- let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
- urlComponents.percentEncodedQuery = percentEncodedQuery
- urlRequest.url = urlComponents.url
- }
- } else {
- if urlRequest.headers["Content-Type"] == nil {
- urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
- }
- urlRequest.httpBody = Data(query(parameters).utf8)
- }
- return urlRequest
- }
-
-
-
-
-
-
-
- public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
- var components: [(String, String)] = []
- switch value {
- case let dictionary as [String: Any]:
- for (nestedKey, value) in dictionary {
- components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
- }
- case let array as [Any]:
- for value in array {
- components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
- }
- case let number as NSNumber:
- if number.isBool {
- components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue))))
- } else {
- components.append((escape(key), escape("\(number)")))
- }
- case let bool as Bool:
- components.append((escape(key), escape(boolEncoding.encode(value: bool))))
- default:
- components.append((escape(key), escape("\(value)")))
- }
- return components
- }
-
-
-
-
-
- public func escape(_ string: String) -> String {
- string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
- }
- private func query(_ parameters: [String: Any]) -> String {
- var components: [(String, String)] = []
- for key in parameters.keys.sorted(by: <) {
- let value = parameters[key]!
- components += queryComponents(fromKey: key, value: value)
- }
- return components.map { "\($0)=\($1)" }.joined(separator: "&")
- }
- }
- public struct JSONEncoding: ParameterEncoding {
-
-
- public static var `default`: JSONEncoding { JSONEncoding() }
-
- public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) }
-
- public let options: JSONSerialization.WritingOptions
-
-
-
-
- public init(options: JSONSerialization.WritingOptions = []) {
- self.options = options
- }
-
- public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
- var urlRequest = try urlRequest.asURLRequest()
- guard let parameters = parameters else { return urlRequest }
- do {
- let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
- if urlRequest.headers["Content-Type"] == nil {
- urlRequest.headers.update(.contentType("application/json"))
- }
- urlRequest.httpBody = data
- } catch {
- throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
- }
- return urlRequest
- }
-
-
-
-
-
-
-
-
- public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
- var urlRequest = try urlRequest.asURLRequest()
- guard let jsonObject = jsonObject else { return urlRequest }
- do {
- let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
- if urlRequest.headers["Content-Type"] == nil {
- urlRequest.headers.update(.contentType("application/json"))
- }
- urlRequest.httpBody = data
- } catch {
- throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
- }
- return urlRequest
- }
- }
- extension NSNumber {
- fileprivate var isBool: Bool {
-
-
- String(cString: objCType) == "c"
- }
- }
|