Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post application/x-www-form-urlencoded Alamofire

I want to use Alamofire to retrieve a bearer token from Web API but I am new to ios and alamofire. How can I accomplish this with Alamofire?

func executeURLEncodedRequest(url: URL, model: [String : String]?, handler: RequestHandlerProtocol) {
    addAuthorizationHeader()
    Alamofire.request(.POST,createUrl(url), parameters: model, headers: headers,encoding:.Json)
}
like image 502
Mario Dennis Avatar asked May 12 '16 05:05

Mario Dennis


2 Answers

Well you don't really need Alamofire to do this (it can be simply done using a plain NSURLRequest) but here goes:

let headers = [
    "Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
    "myParameter": "value"
]
let url = NSURL(string: "https://something.com")!
Alamofire.request(.POST, url, parameters: parameters, headers: headers, encoding: .URLEncodedInURL).response { request, response, data, error in
    print(request)
    print(response)
    print(data)
    print(error)
}

I think that the headers can be omitted since alamofire will append the appropriate Content-Type header. Let me know if it works.

You can also find a ton of specification with examples here.

like image 63
Majster Avatar answered Nov 07 '22 23:11

Majster


Alamofire 4.7.3 and Swift 4.0 above

As per the documentation for POST Request With URL-Encoded Parameters

let parameters: Parameters = [
    "foo": "bar", 
    "val": 1 
]

// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

// HTTP body: foo=bar&val=1

Alamofire 5.2

let parameters: [String: [String]] = [
    "foo": ["bar"],
    "baz": ["a", "b"],
    "qux": ["x", "y", "z"]
]

// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))

// HTTP body: "qux[]=x&qux[]=y&qux[]=z&baz[]=a&baz[]=b&foo[]=bar"
like image 15
Suhit Patil Avatar answered Nov 07 '22 23:11

Suhit Patil