Post Requests in Alamofire Parameter Encoding Returning Get Responses

POST requests in Alamofire Parameter Encoding returning GET responses

Turned out that the problem was a combination of the command that Alamofire.request() generates (curl -i -X POST...) and how my Apache was handling trailing slashes of the URL. So when I tried to POST "http://192.168.0.106/users" I was being redirect (301) to a GET "http://192.168.0.106/users".

So I had to include this line of command in my .htaccess:

# Redirect Trailing Slashes...
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)/$ /$1 [L,R=301]

and change my Router's code, always appending a trailing slash at the end:

var route: String {

switch self{

case .Users:
return ""
case .ReadUser(let userID):
return "/\(userID)/"
case .CreateUser:
return "/"
case .UpdateUser(let userID):
return "/\(userID)/"
case .DestroyUser(let userID):
return "/\(userID)/"
}

}

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)
}
}
}

:)

Swift Alamofire POST request becomes GET

I had the same problem, you just have to put / at the end of URL. Problem is in Alamofire, I think. It works weird with normal server redirections from www.domain.com/something to www.domain.com/something/

How to write alamofire request function that returns the response?

You can pass a closure as a parameter to the function like this

func callAPI(params: Dictionary<String, Any>, url: String, completion:@escaping (((Dictionary<String,Any>?) -> Void))) -> Void {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.contentColor = UIColor.red
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding(options: []), headers: nil).responseJSON { response in
hud.hide(animated: true)
switch response.result{
case .success:
if let resultJson = response.result.value as? Dictionary<String,Any>{
print(resultJson)
completion(resultJson)
// Success
}
case .failure(let error):
print(error)
completion(nil)
//Failed
}
}
}

Call the function with the closure

callAPI(params: [:], url: "") { resultJson in
guard let resultJson = resultJson else {
return
}
print(resultJson)
}


Related Topics



Leave a reply



Submit