Cannot get the POST request to work AlamoFire and XCode/Swift - ios

I am using Swift and Xcode and am trying to send a Post request. A normal request without parameters and no method declaration is working. However, when I try to do a specific post request with parameters it no longer works. I have taken the logic straight from Alamofire's documentation. I have included some pictures and code below.
let parameters = ["barcdodeNumber": displayValue]
AF.request(url, method: .post, parameters: parameters)
//this is the right way, but it does not work
AF.request(url).response { response in
debugPrint(response)
}
//this is wrong but it works

You need to call one of the response methods, e.g.,
AF.request(url, method: .post, parameters: parameters).response { response in
debugPrint(response)
}
This begs the question as to what your endpoint returns. Usually it’s JSON, so you’d use responseJSON or one of the decoder renditions.

Ultimately this was the way that ended up working correctly.
AF.request(url, method: .post, parameters: params, encoding:
URLEncoding(destination: .queryString)).response { response in
debugPrint(response)
}

Related

Alamofire POST request with nested parameters returns nothing

Hello I am trying to use Alamofire for my HTTP requests. It is working with parameters that are not included any nested parameter. Normally, my url is working with following on the Google Chrome.
http://111.222.33.4:12345/my_server/dispatch?cmd=ext_getReferanceData&jp=%7b%22rfName%22:%22RF_ABC%22%7d&token=123
and the decoded version of above url is
http://111.222.33.4:12345/my_server/dispatch?cmd=ext_getReferanceData&jp={"rfName":"RF_ABC"}&token=123
It works fine when I paste it into any browser. However when I try to send following post request with Alamofire
let parameters3: [String: Any] = [
"cmd": "ext_getReferanceData",
"jp": [
"rfName": "RF_ABC"
],
"token": "123"
]
Alamofire.request("http://111.222.33.4:12345/my_server/dispatch", method: .get, parameters: parameters3, encoding: JSONEncoding.default).responseJSON { (response) in
}
It is returning
FAILURE:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
What could be the reason of it am I sending parameters wrong or is there anything that I am missing?
Edit: I also checked other questions about the error but the problem is about parameters that I am trying to send because there is " and { in the parameters but I could not send in the request.
have you considered printing the response being sent and confirming it that it's indeed the stuff you're trying to send?
You can do a couple of things to improve
Make the method .post
Try to use .validate() for added reliability
The way I do it is something like:
let submissionURL = URL(string: "https://blablabla.com/script.php")
sendAlamofireRequest(submissionURL: submissionURL!, parameters: parameters, chosenTrackerStr: chosenTrackerString) //function call
//function declaration
func sendAlamofireRequest(submissionURL: URL, parameters: Parameters, chosenTrackerStr: String){
Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() { (response) in
//actual code goes here
}
}
Maybe try to play around with the alamofire request and check its documentation to see the suggested approach :)

Alamofire post request error Extra argument 'method' in call

I'm using xcode 9.2 I want to make a post request however I'm getting this error "Extra argument 'method' in call". I know it's talking about the post method but i dont know how to fix it, can anyone help?
Alamofire.request(URL_REGISTER, method: .post, parameters: body, encoding: JSONEncoding, headers: header).responseString {
(response) in
if response.results.error == nil {
completion(true)
} else {
completion(false)
debugPrint(response.resultd.error as Any)
}
}
your attributes probably aren't valid (if the types don't match Xcode will tell you the error with the closest matching function)
try changing JSONEncoding to JSONEncoding.default and that your body matches [String:Any]
Alamofire.request(String, method: HTTPMethod.post, parameters: [String:Any], encoding: JSONEncoding.default, headers: header)
something along these lines (I don't know about the header attribute I usually have this at nil)
It probably is because your body variable isn't [String: Any]

Alamofire: syntax for writing a POST request with url, method, parameters, headers and encoding

I've had a look at tons of previous answers, but couldn't find an up-to-date one that includes ALL the following parameters: url, method, parameters, encoding, headers.
This:
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { ... }
Gives the error: Extra argument "method" in call
UPDATE 26/06/2017
The format of the request is actually correct, the issue is that the format of one parameter sent was incorrect. The error is pretty misleading. See my answer below for a list of the parameter's types required and their default value.
Cristallo's answer is a great custom way to do it.
In the meantime, I've discovered that the request in my original question actually works, at the condition that the value passed to the parameter headers is of type [String: String].
Alamofire's error is a bit misleading:
Extra argument 'method' in call.
Here is therefore the request that can be used:
Alamofire.request(
url,
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: httpHeaders).responseJSON { response in
...
}
With the parameters types expected and their default values (taken from Alamofire source code):
Alamofire.request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
the easiest way is to create a specific request and then customize it using Request methods and properties
var request = URLRequest(url: yourUrl)
request.httpMethod = yourMethod
request.setValue(yourCustomizedValue)
request.httpBody = yourBody
...
Alamofire.request(request).responseJSON {...}

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

Pass parameter with json field when invoking POST in Alamofire

I have encountered an issue in swift 3:
I have an API which I need to access for data in my app, but the parameter that it demands is in the following format:
"jsonRequest" = {
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
}//this is in json format.
I tried to pass this parameter as dictionary to call the API, but at that point I obtained this message error:
Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed
Any one knows how I can solve the problem?
I think you want to pass these things in header of the request.
for that you need to do like this
let headers = ["header": "GetLocationListReq",
"accessKey": "1234567890abcdefghij"]
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON{
r in
//do what you want here
}
hope this will work.
try to post this code
let par:[String:Any] = ["jsonRequest":[
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
]]
pass it like that in Alamofire
Alamofire.request(url, method: .post, parameters: par, encoding: JSONEncoding.default, headers: nil).responseJSON{
r in
//do what you want here
}

Resources