How to pass JSON object in Alamofire request swift 3 - ios

I am doing service calls using Alamofire API. So far GET methods are working fine. And now I need to do a PUT request. Also it is accepting body parameters in this type.
{
"LeaveEntryCode":0,
"RequestId":0,
"EmployeeCode":17227,
"LeaveYear":2017,
"LeaveTypeCode":1,
"LeaveReasonCode":1,
"BaseType":"ess",
"StartDate":"2017-06-16T00:00:00",
"EndDate":"2017-06-16T00:00:00",
"NoOfDays":1.0,
"StartDateSession":"full",
"EndDateSession":"full",
"PreApproved":false,"ForDate":"1901-01-01T00:00:00",
"Remarks":"I have to attend for a wedding of my close relatives",
"CoveringPersonCode":0,
"RequestStatus":"P",
"Deleted":false,
"Status":false,
"CreatedBy":0,
"CreatedDate":"0001-01-01T00:00:00",
"UpdatedBy":0,
"UpdatedDate":"0001-01-01T00:00:00",
"DeletedBy":0,
"DeletedDate":"0001-01-01T00:00:00",
"ModuleId":2,
"ObjectId":20,
"StartDateString":"06/16/2017",
"EndDateString":"06/16/2017",
"LeaveDayList":["06/16/2017-FH,06/16/2017-SH"],
"SystemLeaveTypeCode":"ANN",
"LeaveTypeName":"ANNUAL",
"Employee":null,
"LieuDayList":null,
"BaseLeaveType":"ANN",
"CoveringPersonName":"",
"LeaveReasonName":"Personal",
"DocumentSource":"LEAVE",
"AttachedDocument":null
}
I created a [String:Any] object and assigned to parameters in the following request.
But I got an error called Extra argument 'method' in the call.
But If I assigned it as ["":""] that error disappears. How can I solve this? Please help me.
Alamofire.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headerToken)
UPDATE
var dictionary:[String:String]!
dictionary=[
"LeaveEntryCode":"0",
"RequestId":dm.strReqID,
"EmployeeCode":dm.strEmpCode,
"LeaveYear":dm.selectedYear,
"LeaveTypeCode":dm.selectedLeaveTypeCode,
"BaseType":"ess",
"StartDate":dm.startDate,
"EndDate":dm.endDate,
"NoOfDays":dm.noOFDays,
"StartDateSession":dm.startDateSession,
"EndDateSession":dm.endDateSession,
"RequestStatus":"P",
"PreApproved":"0",
"ForDate":"01/01/1901",
"Remarks":comment,
"CoveringPersonCode":dm.strcoveringPersonCode,
"LeaveDayList":strDayLvList,
"BaseLeaveType":dm.selectedLeaveTypeCode,
"LeaveReasonCode":dm.selectedReasontypeCode,
"AttachedDocument":"null"
]

You got an error called Extra argument 'method' in call which is due to headers,
Try passing headers as nil or as follows :
//Here param equals to your dictionary as [String :Any]
//Pass Headers as Dictionary as well.
Alamofire.request("", method: .post, parameters: param, encoding: JSONEncoding.default, headers:["" : ""])
It Worked for me.
Check this link as well:
Alamofire Swift 3.0 Extra parameter in call

//try this
Alamofire.request(urlString, method: method, parameters: parameters as! Parameters, encoding: JSONEncoding.default, headers: headerToken)

parameters should be of Parameters type not dictionary.
try this:
let parameters: Parameters = [
"LeaveEntryCode":"0",
"RequestId":dm.strReqID,
"EmployeeCode":dm.strEmpCode,
"LeaveYear":dm.selectedYear,
"LeaveTypeCode":dm.selectedLeaveTypeCode,
"BaseType":"ess",
"StartDate":dm.startDate,
"EndDate":dm.endDate,
"NoOfDays":dm.noOFDays,
"StartDateSession":dm.startDateSession,
"EndDateSession":dm.endDateSession,
"RequestStatus":"P",
"PreApproved":"0",
"ForDate":"01/01/1901",
"Remarks":comment,
"CoveringPersonCode":dm.strcoveringPersonCode,
"LeaveDayList":strDayLvList,
"BaseLeaveType":dm.selectedLeaveTypeCode,
"LeaveReasonCode":dm.selectedReasontypeCode,
"AttachedDocument":"null"
]

Make the parameters of type [String:AnyObject]? and depending on whether you need parameters or not assign value to it or set it as nil. For headers make it of type [String:AnyObject]?. So if you don't have header make it nil. For example
var dictionary:[String:String]?
if shouldAddParams{
dictionary=[
"LeaveEntryCode":"0",
"RequestId":dm.strReqID,
"EmployeeCode":dm.strEmpCode,
"LeaveYear":dm.selectedYear,
"LeaveTypeCode":dm.selectedLeaveTypeCode,
"BaseType":"ess",
"StartDate":dm.startDate,
"EndDate":dm.endDate,
"NoOfDays":dm.noOFDays,
"StartDateSession":dm.startDateSession,
"EndDateSession":dm.endDateSession,
"RequestStatus":"P",
"PreApproved":"0",
"ForDate":"01/01/1901",
"Remarks":comment,
"CoveringPersonCode":dm.strcoveringPersonCode,
"LeaveDayList":strDayLvList,
"BaseLeaveType":dm.selectedLeaveTypeCode,
"LeaveReasonCode":dm.selectedReasontypeCode,
"AttachedDocument":"null"
]
} else {
dictionary = nil
}

Related

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

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

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 {...}

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