Alamofire 4 Swift 3 Parameter Encoding Custom

I upgraded my project to Swift 3 and Alamofire 4. I used custom encoding, but changed it to other encoding methods. I cannot find an alternative / equivalent to this:

alamoFire.request(urlString, method: HTTPMethod.post, parameters: [:], encoding: .Custom({ (convertible, params) in let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest let data = (body as NSString).data(using: String.Encoding.utf8) mutableRequest.httpBody = data return (mutableRequest, nil) }), headers: headers()).responseJSON { (responseObject) -> Void in switch responseObject.result { case .success(let JSON): success(responseObject: JSON) case .failure(let error): failure(error: responseObject) } } 

I also tried to make the URLRequest object and a simple request of it also giving me errors

 var request = URLRequest(url: URL(string: urlString)!) let data = (body as NSString).data(using: String.Encoding.utf8.rawValue) request.httpBody = data request.httpMethod = "POST" request.allHTTPHeaderFields = headers() alamoFire.request(request).responseJSON { (responseObject) -> Void in switch responseObject.result { case .success(let JSON): success(JSON) case .failure(let error): failure(responseObject, error) } } 

Call me in a specific direction how to connect httpbody using Alamofire 4

+9
ios swift3 alamofire
Sep 19 '16 at 12:43
source share
2 answers

In Alamofire 4.0 you must use the ParameterEncoding protocol. Here is an example that makes any String UTF8 encoded.

 extension String: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var request = try urlRequest.asURLRequest() request.httpBody = data(using: .utf8, allowLossyConversion: false) return request } } Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:]) 
+11
Sep 19 '16 at 13:00
source share

Try this method?

 Alamofire.request(url, method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseObject(completionHandler: { (response : DataResponse<T>) in }) 
+8
Sep 19 '16 at 13:02
source share



All Articles