Alamofire with -d
I need to make request like this Postman one, but in Alamofire
curl -X DELETE \
http://someUrl \
-H 'authorization: JWT someToken' \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-H 'postman-token: 0149ef1e-5d45-34ce-3344-4b658f01bd64' \
-d id=someId
I guess it should be something like:
let headers = ["Content-Type": "application/x-www-form-urlencoded", "Authorization": "JWT someToken"]
let params: [String: Any] = ["id": "someId"]
Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers).validate().responseJSON { responseJSON in
switch responseJSON.result {
case .success( _):
let data = responseJSON.result.value!
print(data)
case .failure(let error):
print(error.localizedDescription)
}
}
How can I check that my request has option like this from cUrl
- -d id=someId
Solution 1:
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"