Post json encode parameter swift - ios

Can you suggest me how to pass following parameter in swift or objective c
let parameters = ["Access_Key":"0699DADD8A2B5FC2E8FF6FF5DDFE03EEDB3ED2132B29EA4F28","Packages":["Length":self.Length,"Type":"","Kg":self.Weight,"Height":self.Height,"Width":self.Width,"Name":self.SkuName],
"issignaturerequired":"true",
"Outputs":["LABEL_PNG_100X175"],
"DeliveryReference":"86882",
"Destination":["ContactPerson":self.CustomerFirstname,"Address":["PostCode":self.PostalCode,"StreetAddress":self.Address1,"Suburb":self.City,"BuildingName":"","City":self.City,"CountryCode":"AU"],"PhoneNumber":"","Email":self.CustomerEmail,"Name":self.CustomerFirstname],
"PrintToPrinter":"true",
"SendTrackingEmail":"",
"Commodities":["UnitKg":"1.0000","Currency":"NZD","Country":"NZ","Units":"1","Description":"Drums Drum Accessories Drum Bags","UnitValue":"44.0"],
"DeliveryInstructions":"None"
]
Alamofire.request(.POST, "http://api.omniparcel.com/labels/printcheapestcourier",parameters: parameters, encoding: .JSON)
.responseJSON { response in
print(response)
}
}
I am new to iOS

I would recommend you to use EVReflection for your JSON objects in Swift.
Just create an object for your JSON Object and then pass it to Alamofire with myJsonObject.toDictionary() as parameters.

Related

How to use responseDecodable instead of responseJSON using Alamofire 6

One of my apps no longer works due to JSON serialisation failing when using Alamofire.
'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)'
is deprecated: responseJSON deprecated and will be removed in
Alamofire 6. Use responseDecodable instead.
For code with the following lines
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { response in.. }
When changing to
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
.responseDecodable { response in... }
Then I get the error
Generic parameter 'T' could not be inferred
So I add the following
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
.responseDecodable(of: ResponseType.self) { response in.. }
I get the error
Cannot find 'ResponseType' in scope
Does anyone have any suggestions?
Unlike .responseJSON which returns a dictionary or array .responseDecodable deserializes the JSON into structs or classes.
You have to create an appropriate model which conforms to Decodable, in your code it's represented by ResponseType(.self).
The associated value of the success case is the root struct of the model.
But deprecated (in a yellow warning) means the API is still operational.
Side note: A JSON dictionary is never [String: Any?] the value is always non-optional.
In Alamofire -> Documentation/Usage.md, I found the definition of the Decodable, so I try like this, then found working.
struct DecodableType: Decodable {
let url: String
}
AF.request(urlString).responseDecodable(of: DecodableType.self) { response in
switch response.result {
case .success(let dTypes):
print(dTypes.url)
case .failure(let error):
print(error)
}
}

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

How to pass JSON object in Alamofire request swift 3

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
}

Unable to parse JSON response object Alamofire

I am making a post request and get back a JSON response in the form of [Object object]. I tried various ways to parse this JSON but wasn't able to. Whenever I try, I get an error saying Could not cast value of type '__NSCFString' (0x10f3dc4a0) to 'NSData'
On the backend side, I have a NodeJS server that replies with res.send. Do I need to convert this data to something else or is there a way I can parse this JSON Data and get the Dictionary object that I am originally supposed to get. I'm using Swift 3 with Alamofire 4.0.
How can I solve this issue?
This is my request code in iOS
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
let data_temp = try! JSONSerialization.jsonObject(with: response.result.value! as! Data, options: JSONSerialization.ReadingOptions.mutableContainers)
print(data_temp)
}
}

Printing data in Alamofire request

I am trying to print the data returned from an alamofire post request in swift like so:
Alamofire.request(.POST, "http://blablabla.com/test1", parameters: ["operand1": "123"]).response { request, response, data, error in
print(request)
print(response)
print(data, radix: 16)
print(error)
}
but when I try to print data it doesn't print a string a string, instead it prints:
<796570>
I am a bit new to swift so I don't really know if there is a way or a reason for this.
That is the raw server response which is in NSData type. You can make use of some built-in serializers such as .responseString() in order to convert that into user readable value:
Alamofire.request(.POST, "http://blablabla.com/test1", parameters: ["operand1": "123"]).responseString { response in
print("Response String: \(response.result.value)")
}
You can check out other serializers in the Alamofire documentation.

Resources