Alamofire 4 Swift 3 ParameterEncoding Custom

13,663

In Alamofire 4.0 you should use ParameterEncoding protocol. Here is an example, which makes any String UTF8 encodable.

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: [:])
Share:
13,663
Raheel Sadiq
Author by

Raheel Sadiq

Eat, pray, code

Updated on June 11, 2022

Comments

  • Raheel Sadiq
    Raheel Sadiq almost 2 years

    I updated my project to Swift 3 and Alamofire 4. I was using custom Encoding, but it's changed to other encoding methods. I am not able to find the 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 by making URLRequest object and simple request its 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)
            }
        }
    

    Do point me in some direction, how to attach httpbody with the Alamofire 4