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
Using Reflection to Set Object Properties Without Using Setvalue Forkey
Swift - Associated Value or Extension for an Enum
Color Text of Status Bar in Xcode 6-B3 (Swift)
Using the Swift If Let with Logical and Operator &&
Swift Enum with Custom Initializer Loses Rawvalue Initializer
How to Add Nil Value to Swift Dictionary
What Does an Exclamation Mark in a Property in Swift Language
How to Run App in Simulator Xcode 6
Swift Switch Char{ Case "\U{E2}:
Swift Catch Enum Case with Binding
How to Display Mtkview with Rgba16Float Mtlpixelformat
How to Run the Simulator the Operation Couldn't Be Completed. (Launchserviceserror Error 0.)
Alamofire 5 Escaping Forward Slashes
Swift Package Manager with Resources Compile Errors
Swift Check If Value Is of Type Array (Of Any Type)
Which Measuring Unit Is Used in Scnvector3 Position for X, Y and Z in Arkit