Alamofire Custom Parameter Encoding

Vivian  picture Vivian · Aug 6, 2015 · Viewed 9.6k times · Source

I'm using Alamofire and want to encode my parameters with content type "text/html; charset=utf-8". I followed the documentation https://github.com/Alamofire/Alamofire for custom parameter encoding and created

let custom: (URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) = {
    (URLRequest, parameters) in
    let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
    mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
    mutableURLRequest.body =  // don't know if I need to set this
    return (mutableURLRequest, nil)
}

func postData(){
    Alamofire.request(.POST, baseUrl, parameters: parameters, encoding: .Custom(custom))
        .responseString{ (request, response, data, error) in
    println("blah")
    }
}

I have a problem when I try to use custom in my Alamofire request and get the error "Cannot make responseString with argument list of type ( _, _, _, _)-> _ )" However, this isn't a problem if the encoding is changed to a preset like .URL so the issue seems to be in my implementation of custom?

If it makes a difference my parameters are set here:

var parameters = [String: AnyObject]()
func setParams(){
        parameters = [
        "CONTRACT ID" : chosenContract!.iD.toInt()!,
        "FEE AMOUNT" : 0,
        "TRANSACT DATE" : today
    ]
}

Answer

cnoon picture cnoon · Aug 7, 2015

You have a couple questions in here. Let's break them down 1x1.

Compiler Issue

Your compiler issue is due to the fact that your return tuple is the wrong type. In Alamofire 1.3.0, we changed the return type to be an NSMutableURLRequest which ends up making things much easier overall. That should fix your compiler issue.

Setting the HTTPBody

Now you have a couple options here.

Option 1 - Encode Data as JSON

let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data

From what you posted I'm assuming you actually want .URL encoding for the parameters.

Option 2 - Use the .URL Case

let parameters: [String: AnyObject] = [:] // fill in
let encodableURLRequest = NSURLRequest(URL: URL)
let encodedURLRequest = ParameterEncoding.URL.encode(encodableURLRequest, parameters).0

let mutableURLRequest = NSMutableURLRequest(URL: encodedURLRequest.URLString)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")

Alamofire.request(mutableURLRequest)
         .response { request, response, data, error in
             print(request)
             print(response)
             print(error)
         }

Hopefully that helps get you going. Best of luck!