为Alamofire定制URLEncoding

时间:2017-06-23 05:06:04

标签: ios swift alamofire

我遇到了Alamofire URLEncoding的问题,特别是对于参数数组,其中use []分隔符用于解析参数数组。

如何针对这种情况编写自己的URLEncoding?

2 个答案:

答案 0 :(得分:1)

试试获取

struct CustomGetEncoding: ParameterEncoding {
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var request = try URLEncoding().encode(urlRequest, with: parameters)
            request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
            return request
        }
    }

如何使用

 Alamofire.request("url", method: .get, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomGetEncoding()).validate().responseJSON { (response) in

        }

答案 1 :(得分:0)

请使用此字符串扩展名

 public extension String {
    public func URLEncode() -> String {
        return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
      }
    }