How to add Alamofire URL parameters

I have a working script using Postman passing in URL parameters. Now when I try to do this through Alamofire in Swift, it does not work.

How would you create this URL in Alamofire? http: // localhost: 8080 /? test = 123

_url = "http://localhost:8080/" let parameters: Parameters = [ "test": "123" ] Alamofire.request(_url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers 
+7
swift alamofire
source share
2 answers

The problem is that you are using URLEncoding.default . Alamofire interprets URLEncoding.default differently depending on the HTTP method .

For GET , HEAD and DELETE requests, URLEncoding.default encodes the parameters as a query string and adds them to the URL, but for any other method (for example, POST ), the parameters are encoded as a query string and sent as the body of an HTTP request.

To use the query string in a POST request, you need to change your encoding argument to URLEncoding(destination: .queryString) .

You can see more details on how Alamofire handles request parameters here .

Your code should look like this:

  _url = "http://localhost:8080/" let parameters: Parameters = [ "test": "123" ] Alamofire.request(_url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: headers) 
+25
source share

If you want your parameters to be used in querystring, use .queryString as URLEncoding, as in: (I assume you have headers somewhere)

 let _url = "http://localhost:8080/" let parameters: Parameters = [ "test": "123" ] Alamofire.request(_url, method: .post, parameters: parameters, encoding: URLEncoding.queryString, headers: headers) 

This form was proposed by Alamofire because it is more similar to the other, see screenshot: Excerpt from the website

See original here

+6
source share

All Articles