Incorrect response from Alamofire? - ios

I am making a request to a server using Alamofire. Here is how i am doing it:
Alamofire.request(url, method: .post, parameters: [:] ,encoding: JSONEncoding.default).responseJSON { response in
print("response=\(response)")
print("Response=:\((response.response?.statusCode)!)")
switch response.result{
case .success :
let passList = AuthenticateSuccess(nibName: "AuthenticateSuccess", bundle: nil)
self.navigationController?.pushViewController(passList, animated: true)
print("connected")
case .failure(let error):
self.showAlertTost("", msg: "Authentication Failed. Authenticate again!", Controller: self)
}
}
This is what prints:
response=SUCCESS: {
message = "Access denied.";
}
Response=:401
connected
I want to know that if 401 is error why is success block being executed? Is failure case in Alamofire handled differently?

As the documentation says:
By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate() before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.
E.g.
Alamofire.request(url, method: .post, encoding: JSONEncoding.default)
.validate()
.responseJSON { response in
...
}
With validate, non 2xx responses will now be treated as errors.

response.success depicts that the server has returned the response. Whereas 401 is something that is related to the REST response which your backend system generated. Hence add the check to response code after verifying that you have received the response to provide better information to the end-user.

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

How to access redirected URL response from .POST HTTP request

I'm trying to connect to a payment server, which is supposed to redirect me to another URL other than the one I have in my code.
So I used Alamofire (.POST request) to connect to the server but I always enter the error case for "too many HTTP redirects" code=1007
And I know that the server should return that, What I need is to print the URL the server tried to redirect me to in my xcode console.
I have tried to use:
print(response.response?.allHeaderFields)
But didn't help in the output, Couldn't access the redirected URL.
let urlString = "http://www.gazdev.tk/PHP_VPC_3Party_Order_DO.php"
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response.response)
break
case .failure(let error):
print(response.response)
print(error)
}
}
I get this as print statement:
load failed with error Error Domain=NSURLErrorDomain Code=-1007 "too many HTTP redirects"
I think response.response?.url is what you want,eg:
AF.request("https://httpbin.org/get").responseJSON { response in
debugPrint("redirect = \(response.response?.url)")
}

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 - responseSerializationFailed

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

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

Resources