Post Request with Data in Body with Alamofire 4

POST request with data in body with Alamofire 4

You need to send request like below in swift 3

let urlString = "https://httpbin.org/get"

Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)

break
case .failure(let error):

print(error)
}
}

Swift 5 with Alamofire 5:

AF.request(URL.init(string: url)!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
print(response.result)

switch response.result {

case .success(_):
if let json = response.value
{
successHandler((json as! [String:AnyObject]))
}
break
case .failure(let error):
failureHandler([error as Error])
break
}
}

Alamofire post request:

There are many ways to implement the requests using Alamofire, this is a simple example:

First, do you have to create the parameters, URL from your API and headers:

let parameters = [
"username": "foo",
"password": "123456"
]

let url = "https://httpbin.org/post"

static private var headers: HTTPHeaders {
get {
return [
"Authorization" : "Bearer \(Session.current.bearerToken ?? "")"
]
}
}

So you call the function from Alamofire and pass your data:

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
switch (response.result) {
case .success:
print(response)
break
case .failure:
print(Error.self)
}
}
}

:)

Alamofire set request body with Data

Alamfire accepts [String:Any]

 do {
let params = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
Alamofire.request(url, method: .post, parameters:params, encoding: JSONEncoding.default, headers: headers)
request.validate().responseJSON {
...
}
}
catch {
print(error)
}

Swift 4.2

Alamofire.request(url, method: .post, parameters: [:], encoding: "test", headers: [:])  

extension String: ParameterEncoding {

public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}

}

How to send a POST request with BODY in swift

You're close. The parameters dictionary formatting doesn't look correct. You should try the following:

let parameters: [String: AnyObject] = [
"IdQuiz" : 102,
"IdUser" : "iosclient",
"User" : "iosclient",
"List": [
[
"IdQuestion" : 5,
"IdProposition": 2,
"Time" : 32
],
[
"IdQuestion" : 4,
"IdProposition": 3,
"Time" : 9
]
]
]

Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
.responseJSON { request, response, JSON, error in
print(response)
print(JSON)
print(error)
}

Hopefully that fixed your issue. If it doesn't, please reply and I'll adjust my answer accordingly.



Related Topics



Leave a reply



Submit