Alamofire - responseSerializationFailed - ios

I really need help with this one. I'm trying to do POST request using Alamofire, but for some reason I'm always getting an error from the title. When I test in POSTMAN, I'm getting okay response. Here is screenshot from POSTMAN, just to get things clearer:
And this is how I'm calling this API in code:
let parameters: Parameters = [
"data": [
"action":"homeimages"
]
]
print("Params: \(parameters)")
Alamofire.request(Constants.API_URL_2, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON {
response in
print("Response: \(response)")
switch response.result {
case .success(let value):
print("Response: \(value)")
break
case .failure(let error):
print(error)
}
}

As far as I know responseserializationfailed error, mostly error with API itself however as you stated, you are getting response in POSTMAN please check below things :
URL(check small/caps well), parameters are correct(check caps and dictionary format as well)
Sometimes we don't need below (optional) parameter , delete this parameter and check
encoding: JSONEncoding.default

Related

post request with body Alamofire

I am trying to post some data to the API, but I keep getting Response status code was unacceptable: 404 error message.. I have checked, the POST parameters and API Url are all correct, example request works on the postman but it is not working on Xcode..
my POST request Url is in this format: {{API}}/postData/Id/block.
my POST request function with Alamofire is as follows:
func postData(token: String, id: String, category: String, completion: #escaping(_ data: DataTobePost) -> Void) {
let header: HTTPHeaders = ["authorization": token]
let parameter: Parameters = [
"Id": id,
"category": category ]
Alamofire.request(API_Configurator.postData, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: header).validate().responseData(completionHandler: { response in
switch response.result {
case .success(let val):
do {
let data = try JSONDecoder().decode(DataTobePost.self, from: val)
completion(data)
}catch {
print("[DataTobePost Catch Error while decoding response: \(error.localizedDescription)]")
}
case .failure(let error):
print("[DataTobePost Failure Error : \(error.localizedDescription)]")
}
})
}
and the response is:
{
"success": true
}
where am i going wrong, can anyone help through this. (I am quite new to Alamofire)
There is no way to check what is wrong.
If you got the 404 error it means 2 things:
Code was written correctly(it compiles)
Requested page does not exist (404 error)
I think you need to check your API_Configurator.postData.
Usually, it's something simple like extra characters like "//", " ", "." etc.
Or the problem with API.
The best way to check API uses Postman

Alamofire request changes method name on its own

I am using the following code:
func readInfo()
{
let customHeader : HTTPHeaders = [
"X-AUTH-TOKEN" : accessToken
]
let body : Parameters = [
:
]
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 1000
Alamofire.request(requestAddress, method: .get, parameters: body , encoding: JSONEncoding.default, headers: customHeader).responseJSON {
response in
//utility code
}
}
It works perfect when this runs for the first time but when this is run more than once (in say less than 30 seconds), my server gives the error: o.s.web.servlet.PageNotFound : Request method 'T' not supported
Also I get status code 405 in Alamofire response. This is unexpected since I was sending .get request. Why is this happening and how should I avoid it? I am unable to understand.
Also, note that this is not a server error because the requests work as expected when run on Postman.
Try for Alamofire
var parameters = Parameters()
parameters = [
//Your Params
]
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 1000
Alamofire.request("\(url)", method: .get, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON {
response in switch (response.result)
{
case .success(let data):
// your code for success
break
case .failure(let error):
print("Server_Error",error.localizedDescription)
break
}
There were no errors with the cache or timeout. The error was with encoding. I had to save it to URLEncoding.httpBody to make the request work as expected. I still don't understand why it worked once and not for the second time for a certain seconds. Strange case but yes this was the solution. Please leave a comment to help me and others understand why this may have happened.

Alamofire post request returning "<?xml version="1.0" encoding="utf-8"?>"

Using swift 4, I am doing a post request to a web api. The api has correct JSON data but whenever i call it is returning the following response: 
<?xml version="1.0" encoding="utf-8"?>
My code is:
let urlString = "XXXXXXXXXX/ArticlesByListofIds"
Alamofire.request(urlString, method: .post, parameters: ["ids": "160, 145"],encoding: JSONEncoding.default, headers: nil).responseString { response in
switch response.result {
case .success(let responseString1):
print("the response is: \(responseString1)")
break
case .failure(let error):
print("The error is: \(error)")
}
}
Any idea why is this happening?
I see two things happening. First, the API seems to respond with XML rather than JSON, so probably your request is not what you intended it to be. Second, there seems to be an issue with character encoding. This could be anything; maybe a fault in the server configuration, maybe you are decoding the file incorrectly.

Setting content-type header to use JSON with Swift 3 + AlamoFire

The answers in Alamofire Swift 3.0 Extra parameter in call did not work for me.
Setting header to nil compiles but I need ["Content-Type", "application/json"]. Here I get an error of an extra parameter in th emethod
How do I take
manager.request(url, method: .get, parameters: parameters).responseJSON {
response in
fulfill(response)
}
}
and send JSON content-type?
The documentation shows
Automatic Validation
Automatically validates status code within 200..<300 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
I'm using .responseJSON but I'm not getting JSON back. So I think I need to send the Content-Type header.
Try this, there is another method overload that allow pass a dictionary with headers
let request = Alamofire.request(requestUrl, method: .get, parameters: [:], encoding: URLEncoding.queryString, headers: ["Content-Type" :"application/json"]).responseData { (response) in
/***YOUR CODE***/
}
for post JSON data in request check this answer Using manager.request with POST
Hope this helps you

Alamofire extra argument 'method' in call from Alamofire example

I would like to state that I've tried every single example and scanned the plethora of other questions exactly like mine to no avail, so I have NO CHOICE but to post.
Xcode: 8.3.1 (8E1000a)
Apple Swift version 3.1 (swiftlang-802.0.51 clang-802.0.41)
Target: x86_64-apple-macosx10.9
OSX 10.12.4
Please see the code:
Note: This is embedded in a function, the parameters "email" and "password" are strings and are available, I also tried setting static string values.
let url = URL(string: "http://website.what.com/api/v1/login")
let params: Parameters = ["email": email, "password":password]
// This Works
Alamofire.request(url!, method: .post, parameters: params)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
// This one returns: "Extra argument Method in call"
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
The primary I am confident in posting again - the second example was taken straight from the Alamofire github README.
If I am missing something - as in incorrectly encoding a parameter (which I copied directly from Alamofire's github page) or something.
Alternately, if someone can provide me a working sample on Swift 3.1 which allows me to use JSON, Headers, and POST Method.
The first "working" method does not have headers, I am not sure if I can use that example with additional parameters or not?
Sorry for the trouble, very very fresh swift learner who is diving head-first into a complicated world.

Resources