Post JSON Request in Swift

How to send a POST request with BODY in swift

You're close. The parameters dictionary formatting doesn't look correct. You should try the following:

let parameters: [String: AnyObject] = [
"IdQuiz" : 102,
"IdUser" : "iosclient",
"User" : "iosclient",
"List": [
[
"IdQuestion" : 5,
"IdProposition": 2,
"Time" : 32
],
[
"IdQuestion" : 4,
"IdProposition": 3,
"Time" : 9
]
]
]

Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
.responseJSON { request, response, JSON, error in
print(response)
print(JSON)
print(error)
}

Hopefully that fixed your issue. If it doesn't, please reply and I'll adjust my answer accordingly.

post json request in swift

You need to send a valid format of JSON.
“firstName=James&lastName=Bond”; is not JSON format.

Swift 4

Since Swift 3 and 4 Apple is starting to remove NS* stuff (even that many of them are just aliases to NS*) we'll use more Swift way

//Method just to execute request, assuming the response type is string (and not file)
func HTTPsendRequest(request: URLRequest,
callback: @escaping (Error?, String?) -> Void) {
let task = URLSession.shared.dataTask(with: request) { (data, res, err) in
if (err != nil) {
callback(err,nil)
} else {
callback(nil, String(data: data!, encoding: String.Encoding.utf8))
}
}
task.resume()
}

// post JSON
func HTTPPostJSON(url: String, data: Data,
callback: @escaping (Error?, String?) -> Void) {

var request = URLRequest(url: URL(string: url)!)

request.httpMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.httpBody = data
HTTPsendRequest(request: request, callback: callback)
}

Usage example

var dict = Dictionary<String, Any>()

dict["username"] = "hello"
dict["password"] = "swift"
let data = try JSONSerialization.data(withJSONObject: dict, options: [])

HTTPPostJSON(url: "http://example.com/login", data: data) { (err, result) in
if(err != nil){
print(err!.localizedDescription)
return
}
print(result ?? "")
}


Swift < 4

func HTTPsendRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession()
.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if (error != nil) {
callback("", error.localizedDescription)
} else {
callback(NSString(data: data,
encoding: NSUTF8StringEncoding)! as String, nil)
}
}

task.resume()
}

func HTTPPostJSON(url: String, data: NSData,
callback: (String, String?) -> Void) {

var request = NSMutableURLRequest(URL: NSURL(string: url)!)

request.HTTPMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.HTTPBody = data
HTTPsendRequest(request, callback: callback)
}

Usage example

we'll set NSMutableDictionary and convert it to JSON

var json = NSMutableDictionary()
json.setValue("testuser123", forKey: "name"); //set all your values..

let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(0), error: nil);
HTTPPostJSON("http;..", data:data!) { (response, error) -> Void in
println(response);
}

How to send a POST request through Swift?

I think you should pass your request instead of the url to session.dataTask

here is how my code looks like:

private let url = URL(string: "http://example.com/")!

func httpPost(jsonData: Data) {
if !jsonData.isEmpty {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData

URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
NSLog("open tasks: \(openTasks)")
}

let task = URLSession.shared.dataTask(with: request, completionHandler: { (responseData: Data?, response: URLResponse?, error: Error?) in
NSLog("\(response)")
})
task.resume()
}
}

How can I post request with order of json in swift with alamofire?

JSON order isn't typically important, as the JSON spec doesn't define it as a requirement for JSON objects, but some poorly engineered backends do require it. You really need to check the requirements of the backend you're communicating with.

Additionally, Swift's Dictionary type is arbitrarily ordered, and that order may change between runs of your app as well as between versions of Swift used to compile your code.

Finally, Swift's JSONEncoder, and Apple's JSONSerialization type both offer no way to require strict ordering. At most, JSONSerialization offers the .sortedKeys option, which will give you a guaranteed (alphabetical) order, but it may not be the order you declared your parameters in. Using an alternate Encoder, if you have Codable types (which I recommend instead of SwiftyJSON), may give you a better guarantee of order, but you should only really care if it's a requirement of your backend.

As an aside, I suggest you use the static HTTPHeader properties for your HTTPHeaders value, instead of using raw strings, it's much more convenient. For example:

let headers: HTTPHeaders = [.accept("application/json"),
.contentType("application/json")]

How to create JSON Body for Post request in swift

Try using Swift 4's Encodable to create JSON.

Example:

struct Body: Encodable {
var from: String
var to: String
var rooms: [Room]

init(from: String, to: String, rooms: [Room]) {
self.from = from
self.to = to
self.rooms = rooms
}
}

struct Room: Encodable {
var age: Int
var adults: Int
var children: Int

init(age: Int, adults: Int, children: Int) {
self.age = age
self.adults = adults
self.children = children
}
}

let body = Body(from: "Amsterdam", to: "Dubai", rooms: [Room(age: 22, adults: 1, children: 0), Room(age: 54, adults: 0, children: 1)])
let encoded = try JSONEncoder().encode(body)
//String(data: encoded, encoding: .utf8)
//{"from": "Amsterdam", "to": "Dubai", "rooms": [{"age":22,"children":0,"adults":1},{"age":54,"children":1,"adults":0}]}

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

How to post this JSON data as HTTP body using URLSession?

With JSONSerialization:

let params: [String: Any] = ["quizId": 1,
"quizQuestionBanks": [["quizQuestionBankId": 4,
"question": "string",
"option1": "string",
"option2": "string",
"option3": "string",
"option4": "string",
"answer": "Guy de Maupassant",
"explanation": "string"]]]

let jsonData = try? JSONSerialization.data(withJSONObject: params)

But, since Swift 4, we can use Codable:

struct Quiz: Codable {
let id: Int
let questions: [Question]

enum CodingKeys: String, CodingKey {
case id = "quizId"
case questions = "quizQuestionBanks"
}
}

struct Question: Codable {
let id: Int
let question: String
let option1: String
let option2: String
let option3: String
let option4: String
let answer: String
let explanation: String

enum CodingKeys: String, CodingKey {
case id = "quizQuestionBankId"
case question
case option1
case option2
case option3
case option4
case answer
case explanation
}
}

let questions = [Question(id: 4, question: "string", option1: "string", option2: "string", option3: "string", option4: "string", answer: "Guy de Maupassant", explanation: "string")]
let quiz = Quiz(id: 1, questions: questions)
let jsonData = try JSONEncoder().encode(quiz)

option1, option2, option3, option4, could be an array in struct (that would need a custom encoding/decoding).



Related Topics



Leave a reply



Submit