Post Parameter to Sever Using Dictionary Swift

How to send a POST request with nested Dictionary in swift

Thanks to all,
I solve This problem.
Here is the step by step solution to this question.
1)

 Alamofire.request(url, method : .post , parameters : parameter , encoding : JSONEncoding.default, headers : tiket ).responseJSON { (response) in
if response.result.isSuccess{
let responseJoson : JSON = JSON(response.result.value!)
print(responseJoson)
}

encoding is very important here. Don't skip this.
Step 2)

 func apiCall(){
let customerTckt:[String:Any] = ["RequestID" : requestID ,
"TaskID" : taskID ,
"Description" : comments ,
"TicketTypeID" : 3 ,
"CustomerID" : customerID ,
"PriorityID" : 3 ,
"CustomerTPPID" : TTPIDArray ]

let param : [String : Any] = ["ServiceReqID" : 1 ,
"WebUsersID" : customerID,
"FirstName" : userName,
"LastName" : "" ,
"Company":self.profileValues.customerCompanyName ,
"City" : self.profileValues.customerCityName ,
"Email" : self.profileValues.customerEmail ,
"ContactNo" : self.profileValues.customerContactNumber ,
"Country" : "Pakistan" ,
"PackageChange" : 0 ,
"AddressChange" : 0,
"TelInternetVAS" : 0 ,
"Others" : 0 ,
"Comments" : comments ,
"CSAFNO" : self.profileValues.customerCSAFNo,
"SecondaryContactNo" : "" ,
"CustomerTicket" :customerTckt]
let userToken: HTTPHeaders = [
"Authorization": "bearer \(accessToken)",
"Content-Type": "application/json"
]
postserviceRequestFeedback(url: postRequestFeedbackUrl, parameter: param , tiket: userToken)
}

Don't skip "Content-Type" to application/json

Swift - Use dictionary to pass data to params

let arr = zip(arrNumber,arrName).map { ["mobile":$0,"name":$1] }
var parameters: [String: Any] = ["invitations": arr]
print(parameters)//["invitations": [["name": "Paul", "mobile": "1234456"], ["name": "Paul1", "mobile": "1234456"], ["name": "Paul2", "mobile": "1234456"]]]
do {
let json = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
let convertedString = String(data: json, encoding: .utf8)
print(convertedString)

} catch let error {
print(error.localizedDescription)
}

{ "invitations": [
{
"name": "Paul",
"mobile": "1234456"
},
{
"name": "Paul1",
"mobile": "1234456"
},
{
"name": "Paul2",
"mobile": "1234456"
} ] }

pass a dictionary item as a parameter

I am not sure exactly what you want to pass to the other function but you should use the function randomElement()

girlsName.randomElement() // a random key/value pair

girlsName.keys.randomElement() // a random key

girlsName.values.randomElement() // a random value

So if you want to pass a name (value) it could look like

submite(randomVal: girlsName.values.randomElement() ?? "")

if submite is declared as

func submite(randomVal: String) 

Can't make post request using params as dictionary with Swift 4 & Alamofire

From what actually works for you it looks like you need to encode the parameters in the same style as a query. Try this:

struct ParameterQueryEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = parameters?
.map { "\($0)=\($1)" }
.joined(separator: "&")
.data(using: .utf8)
return request
}
}

You should then be able to perform the original call that you had before:

Alamofire.request(urlString,
method: HTTPMethod.post,
parameters: parameters,
encoding: ParameterQueryEncoding(),
headers: headers)
.responseJSON { response in
...
}

How can I make a post request in Swift that reads more than 1 parameter?

I don't think the JSON data you were providing in parameters was valid (I check using jsonlint.com) Try this:

func postRequest(classroomID: String, email: String, vote: String){

//declare parameter as a dictionary which contains string as key and value combination.
let parameters: [String:Any] = [
"classroomID": classroomID,
"LastUpdated": "2020-01-01",
"TheVoteData":[
"Email": email,
"TheVote": vote
]
]

//create the url with NSURL
let url = URL(string: "https://www.api-gateway/dynamoDB/resource")!

//now create the Request object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST

do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
print(error.localizedDescription)
}

//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
//create dataTask using the session object to send data to the server
let task = URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print(dataString)
}
//Returns HHTP response if
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
}
}

task.resume()
}


Related Topics



Leave a reply



Submit