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?
Just separating structs for GET and POST also works.
http://matsue.github.io/post/how-to-remove-square-brackets-with-alamofire/
Alamofire 4 with Swift 3
// Remove square brackets for GET request 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 } } // Remove square brackets for POST request struct CustomPostEncoding: ParameterEncoding { func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var request = try URLEncoding().encode(urlRequest, with: parameters) let httpBody = NSString(data: request.httpBody!, encoding: String.Encoding.utf8.rawValue)! request.httpBody = httpBody.replacingOccurrences(of: "%5B%5D=", with: "=").data(using: .utf8) return request } } // Use structs for requests Alamofire.request("http://example.com", method: .get, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomGetEncoding()) Alamofire.request("http://example.com", method: .post, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomPostEncoding())
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With