korgx9 korgx9 - 13 days ago 5
Swift Question

Alamofire 3 Custom Encoding To Alamofire 4 Custom Encoding

I have method writing in Alamofire 3 with customParameterEncoding. This custom encoding just replaces "[]=" with "=" in queryString and returns it.

Alamofire.request(.GET, SearchURL, parameters: params, encoding: customEncoding, headers: headers).validate().responseJSON {
response in
switch response.result {
case .success:
print("success")
break
case .failure(let error):
print("Error: " + error.localizedDescription)
break
}
}


and custom encoding parameter

let customEncoding = ParameterEncoding.Custom { requestConvertible, parameters in
let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters)
mutableRequest.URL = NSURL(string: mutableRequest.URLString.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "="))
return (mutableRequest, error)
}


How to convert customEncoding to Alamofire 4 version?

Answer

In Alamofire 4.0 you should use ParameterEncoding.

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