Alamofire with -d

You do this:

Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers).validate().responseJSON { ... }

In fact, it can be deconstruct like that:

let request = Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers)

request.validate().responseJSON { ... }

request is a DataRequest, which inherits from Request which has a pretty override of debugDescription that calls curlRepresentation().

If you print request, you’ll have:

$> CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
    atyp = http;
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = http;
    "r_Attributes" = 1;
    sdmn = someUrl;
    srvr = someUrl;
    sync = syna;
}
$ curl -v \
    -X DELETE \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
    -H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 11.4.0) Alamofire/4.7.3" \
    -H "Accept-Language: en;q=1.0, fr-FR;q=0.9" \
    "http://someUrl?id=someId"

Pretty cool, right? But no -d option. You can even check it with print(request.request.httpBody) and get:

$> nil

To fix it, use the encoding (ParameterEncoding) parameter in the init. You can use by default JSONEncoding, URLEncoding and PropertyListEncoding.

But you want to put the parameter in the httpBody, so use URLEncoding(destination: .httpBody):

Alamofire.request("http://someUrl", method: .delete, parameters: params, encoding: URLEncoding(destination: .httpBody), headers: headers)

And you’ll get:

$>CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
    atyp = http;
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = http;
    "r_Attributes" = 1;
    sdmn = someUrl;
    srvr = someUrl;
    sync = syna;
}
$ curl -v \
    -X DELETE \
    -H "Authorization: JWT someToken" \
    -H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 11.4.0) Alamofire/4.7.3" \
    -H "Accept-Language: en;q=1.0, fr-FR;q=0.9" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
    -d "id=someId" \
    "http://someUrl"

Leave a Comment