How can I send swift json to django server? - json

Swift code:
static func send(url: URL, data: Data) async {
var request = URLRequest(url: url)
request.httpMethod = "POST"
let json: [String: Any] = [
"order_details": ["meal_id":"6", "quantity":"1"],
"restaurant_id": "1",
"access_token": "FUJMNpU77OyuLiohOl5wzRQkGpHleV",
"address": "13"
]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
request.httpBody = jsonData
print(String(data: jsonData ?? Data(), encoding: .utf8))
do {
let (_, response) = try await URLSession.shared.data(for: request)
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, 200..<300 ~= statusCode else {
throw URLError(.badURL)
}
} catch {
print(error)
}
}
Print:
Optional("{\"address\":\"13\",\"order_details\":{\"quantity\":\"1\",\"meal_id\":\"6\"},\"restaurant_id\":\"1\",\"access_token\":\"FUJMNpU77OyuLiohOl5wzRQkGpHleV\"}")
JSON looks normal.
BUT in my django server I get this:
if request.method == "POST":
print(request.POST)
Print:
<QueryDict: {'{"address":"13","order_details":{"quantity":"1","meal_id":"6"},"restaurant_id":"1","access_token":"FUJMNpU77OyuLiohOl5wzRQkGpHleV"}': ['']}>
i.e. my request becomes a key
I tried to compose the request in different ways, I used JSONEncoder and JSONSerializer but nothing happened

Related

How to get particular 'json' value in swift 5?

I want the 'success' value in json object but the problem is I'm getting whole json data I want only 'success' value to print
Here is my json`
{
response = {
success = 1;
successmsg = "Successful Connection";
};
}`
Here is my code in swift 5
#IBAction func girisButtonTap(_ sender: Any) {
var txtusername: String
var txtpassword: String
txtusername = usercodeText.text!
txtpassword = passwordText.text!
let Url = String(format: "http://10.10.10.53:8080/sahambl/rest/sahamblsrv/userlogin")
guard let serviceUrl = URL(string: Url) else { return }
let parameters: [String: Any] = [
"request": [
"xusercode" : "\(txtusername)",
"xpassword": "\(txtpassword)"
]
]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
request.timeoutInterval = 20
let session = URLSession.shared
struct ResponseJSON: Codable {
let response: Response
}
struct Response: Codable {
let success: Int
let successmsg: String
}
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONDecoder().decode(ResponseJSON.self, from: data)
print(json)
let successful = json.response.success == 1
} catch {
print(error)
}
}
}.resume()
}
}
I would be grateful for any progress.
Use a model struct and Codable for parsing:
struct ResponseJSON: Codable {
let response: Response
}
struct Response: Codable {
// depending on what your JSON actually looks like, this could also be
// let success: Bool
let success: Int
let successmsg: String
}
session.dataTask(with: request) { data, response, error in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONDecoder().decode(ResponseJSON.self, from: data)
print(json)
// access the success property:
let successful = json.response.success == 1
// leave off the "== 1" if it's a Bool
} catch {
print(error)
}
}
}.resume()

Passing JSON data from HTTP request to another view controller in Swift 3

How to pass the JSON data from HTTP request to another view controller in swift 3? This function is when selected a cell, It will get the JSON data from server then I have to pass the JSON data to another view controller.
func retrieveTime(jobDateValue: String) -> Void {
if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String{
let param = ["action": "retrieve time", "job": ["crew_id": crewID, "jobDate": jobDateValue]] as [String : Any]
let headers = [
"content-type": "application/json",
"cache-control": "no-cache"
]
if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {
let request = NSMutableURLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
_ = URLSession.shared
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [.mutableContainers])) as? NSDictionary
{
let result = json["result"] as? String
if (result == "success") {
let passValue = json
}else{
}
}
})
}
task.resume()
}
}
}
passing json data to second view controller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SecondVCSegue"{
if let destination = segue.destination as? SecondVC {
destination.passedData = json
}
}
}
JSON Output:
{
jobs = (
{
jobDate = "2017-09-01";
jobEndTime = 1504231200;
jobID = 88;
jobTime = 1504224000;
}
);
message = "Retrieve Sucessfully";
result = success;
}
You should set up a manual segue in Storyboard, that you only call inside the completion handler of your network request. If the segue is connected to a single tableview cell, it will be called by the system before your async function would finish execution. Once you changed your segue to be manual and not connected to a static table view cell, you can call it using the function performSegue.
func retrieveTime(jobDateValue: String) -> Void {
if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String{
let param = ["action": "retrieve time", "job": ["crew_id": crewID, "jobDate": jobDateValue]] as [String : Any]
let headers = [ "content-type": "application/json", "cache-control": "no-cache" ]
if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {
var request = URLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
guard error == nil, let data = data else {return}
DispatchQueue.main.async{
if let json = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any]{
let result = json["result"] as? String
if (result == "success") {
let passValue = json
self.performSegue(withIdentifier: "YourSegue", sender: json)
} else{
}
}
}
}
task.resume()
}
}
}
Also use native Swift objects when available instead of their Foundation counterparts (such as NSDictionary, NSMutableURLRequest).
You should also use the sender option of performSegue to send the json data to your other view controller instead of storing it in another variable unless you use the json object in your first view controller as well.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SecondVCSegue"{
if let destination = segue.destination as? SecondVC, let json = sender as? [String:Any] {
destination.passedData = json
}
}
}

Get JSON Results with POST Request with Parameters

How can I use a POST request with parameters to get JSON? I know how to do it with a simple GET request. The request url is http://gyminyapp.azurewebsites.net/api/Gym and the parameter query is
{
"SearchCircle": {
"Center": {
"Latitude": 0,
"Longitude": 0
},
"Radius": 0
},
"City": "string",
"ZipCode": 0,
"Type": "string"
}
I'm wanting to just use the search circle portion of this, which means I can ignore the City and ZipCode fields. I need to provide Latitude/Longitude, which I getting from the current user location. I also need to set the Type to "radius".
For a simple GET request using the GET version of this, I do this.
let url = NSURL(string: "http://gyminyapp.azurewebsites.net/api/Gym")
let data = NSData(contentsOfURL: url!)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
for gym in json as! [AnyObject] {
gyms.append(gym)
}
} catch {
print("Error")
}
This is a working code, you just need to put the values of your request parameters.
let session = NSURLSession.sharedSession()
let url = "http://gyminyapp.azurewebsites.net/api/Gym"
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let params:[String: AnyObject] = ["Type" : "string","SearchCircle" : ["Radius" : 0, "Center" : ["Latitude" : 0, "Longitude" : 0]]]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! NSHTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonResponse = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
print ("data = \(jsonResponse)")
}catch _ {
print ("OOps not good JSON formatted response")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
Then in the if let data = data you'd need to parse the response. I checked the response, it is JSON formatted array.
This is how I did it. Just make an NSDictionary out of params and convert to NSData, I called that postData. And then the usual, send that postData as requestBody
let parameters = [
"SearchCircle":
[ "Center" :
["Latitude" : 0,
"Longitude" : 0] ]
"Radius" : 0,
"City" : "", ...
... and so on
] ]
do
{
let postData = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
let request = NSMutableURLRequest(URL: NSURL(string: "http...")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
print(httpResponse)
do {
// JSON serialization
self.dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSDictionary
// if any data
}
catch {
}
}
})
dataTask.resume()
}
catch {
}
This is the accepted answer's code updated for Swift 4:
let url = "http://gyminyapp.azurewebsites.net/api/Gym"
let session = URLSession.shared
let request = NSMutableURLRequest(url: URL(string: url))
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let params:[String: AnyObject] = ["Type" : "string",
"SearchCircle" : ["Radius" : 0, "Center" : ["Latitude" : 0, "Longitude" : 0]]]
do{
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions())
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
print ("data = \(jsonResponse)")
}catch _ {
print ("OOps not good JSON formatted response")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
}

How to make HTTP Post request with JSON body in Swift?

I'm trying to make an HTTP post request with a JSON body :
How to be able to add an NSdictionnary to the HTTP request body.
Here is my code, it doesn't seem to work properly.
var entry1 = Response(IdQuestion: 6510,IdProposition: 10,Time: 30)
var entry2 = Response(IdQuestion: 8284,IdProposition: 10,Time: 30)
Responses.append(entry1)
Responses.append(entry2)
let list = Responses.map { $0.asDictionary }
let json = ["List":list,"IdSurvey":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]
let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(json)
NSJSONSerialization.isValidJSONObject(json)
let myURL = NSURL(string: "http://www.myserver.com")!
let request = NSMutableURLRequest(URL: myURL)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = data
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
println(response)
// Your completion handler code here
}
task.resume()
Try this,
// prepare json data
let json: [String: Any] = ["title": "ABC",
"dict": ["1":"First", "2":"Second"]]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
or try a convenient way Alamofire
Swift 4 and 5
HTTP POST request using URLSession API in Swift 4
func postRequest(username: String, password: String, completion: #escaping ([String: Any]?, Error?) -> Void) {
//declare parameter as a dictionary which contains string as key and value combination.
let parameters = ["name": username, "password": password]
//create the url with NSURL
let url = URL(string: "https://www.myserver.com/api/login")!
//create the session object
let session = URLSession.shared
//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)
completion(nil, error)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
return
}
do {
//create json object from data
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
return
}
print(json)
completion(json, nil)
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
})
task.resume()
}
#objc func submitAction(_ sender: UIButton) {
//call postRequest with username and password parameters
postRequest(username: "username", password: "password") { (result, error) in
if let result = result {
print("success: \(result)")
} else if let error = error {
print("error: \(error.localizedDescription)")
}
}
Using Alamofire:
let parameters = ["name": "username", "password": "password123"]
Alamofire.request("https://www.myserver.com/api/login", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
HTTP Post in Swift capturing the errors
let json = [ Activity.KEY_IDSUBJECT : activity.idSubject, Activity.KEY_RECORDMODE : "3", Activity.KEY_LOCATION_LONGITUDE : "0",Activity.KEY_LOCATION_LATITUDE : "0", Activity.KEY_CHECKIN : String(activity.dateCheckIn), Activity.KEY_CHECKOUT : String(activity.dateCheckOut) ]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
// create post request
let url = NSURL(string: "https://...appspot.com/_ah/api/activityendpoint/v1/activity")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
return task
} catch {
print(error)
}
Swift 5 answer:
let json: [String: Any] = ["key": "value"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "http://localhost:1337/postrequest/addData")! //PUT Your URL
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(String(describing: jsonData?.count))", forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON) //Code after Successfull POST Request
}
}
task.resume()
The following Swift 5 Playground code shows a possible way to solve your problem using JSONSerialization and URLSession:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "http://localhost:8080/new")!
let jsonDict = ["firstName": "Jane", "lastName": "Doe"]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
var request = URLRequest(url: url)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("error:", error)
return
}
do {
guard let data = data else { return }
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
print("json:", json)
} catch {
print("error:", error)
}
}
task.resume()
let url = URL(string: "url")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
let postString = "ChangeAccordingtoyourdata=\(paramOne)&ChangeAccordingtoyourdata2=\(paramTwo)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
SVProgressHUD.showError(withStatus: "Request has not submitted successfully.\nPlease try after some time")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
SVProgressHUD.showSuccess(withStatus: "Request has submitted successfully.\nPlease wait for a while")
DispatchQueue.main.async {
// enter code
}
}
task.resume()
Perfect nRewik answer updated to 2019:
Make the dictionary:
let dic = [
"username":u,
"password":p,
"gems":g ]
Assemble it like this:
var jsonData:Data?
do {
jsonData = try JSONSerialization.data(
withJSONObject: dic,
options: .prettyPrinted)
} catch {
print(error.localizedDescription)
}
Create the request exactly like this, notice it is a "post"
let url = URL(string: "https://blah.com/server/dudes/decide/this")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8",
forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8",
forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.httpBody = jsonData
Then send, checking for either a networking error (so, no bandwidth etc) or an error response from the server:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("fundamental networking error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
Fortunately it's now that easy.
you can do something like this:
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)
}
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()
}
//use
var data :Dictionary<String, AnyObject> = yourDictionaryData<--
var requestNSData:NSData = NSJSONSerialization.dataWithJSONObject(request, options:NSJSONWritingOptions(0), error: &err)!
HTTPPostJSON("http://yourPosturl..", data: requestNSData) { (response, error) -> Void in
if error != nil{
//error
return;
}
println(response);
}
Swift4 - Apple Solution "POST" and "Codable"
Uploading Data to a Website using request.httpmethod = "Post" and Codable Stucts:
#see: Listing 2 Configuring a URL request
let userlogin = User(username: username, password: password, deviceid:UIDevice.current.identifierForVendor!.uuidString)
guard let uploadData = try? JSONEncoder().encode(userlogin) else {
print("Error UploadData: ")
return
}
let urlUser = URL(string: APPURL.apiURL)!
var request = URLRequest(url: urlUser)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
var responseStatus = 0
let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
if let error = error {
let code = (error as NSError).code
print("Error:\(code) : \(error.localizedDescription)")
completion(code)
return
}
guard let response = response as? HTTPURLResponse else {
print("Invalid response")
return
}
// do your response handling here ...
No library required, simply use URLSession
here is an example:
let sampleData = ["key": "Value"]
var urlRequest = URLRequest(url: URL(string: "https://REPLACE.ME")!)
let urlSession = URLSession = URLSession(configuration: .default)
let encoder = JSONEncoder()
// inside a throwing function or wrap it in a doCatch block
let jsonData = try encoder.encode(sampleData)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json",forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = jsonData
let task = urlSession.dataTask(with: urlRequest) { data, response, error in
let statusCode = (response as? HTTPURLResponse)?.statusCode
print("💁🏻‍♂️ \(statusCode)")
}
task.resume()
A combination of several answers found in my attempt to not use 3rd party frameworks like Alamofire:
let body: [String: Any] = ["provider": "Google", "email": "emailaddress#gmail.com"]
let api_url = "https://erics.es/p/u"
let url = URL(string: api_url)!
var request = URLRequest(url: url)
do {
let jsonData = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
request.httpBody = jsonData
} catch let e {
print(e)
}
request.httpMethod = HTTPMethod.post.rawValue
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
var request = URLRequest(url: URL(string: "http://yogpande.apphb.com/api/my/posttblhouse")!)
request.httpMethod = "POST"
let postString = "email=testname#gmail.com&password=1234567"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
For a Codable / Encodable type in Swift 4+
Use a JSONEncoder to transform the object into Data:
let jsonObject = ... // Encodable or Codable
guard let jsonData = try? JSONEncoder().encode(jsonObject) else {
fatalError("encoding error")
}
Then set that encoded object as the httpBody of the URLRequest:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Swift 5.5
As of Swift 5.5, we now have another alternative using async/await:
// Form the POST request:
let url = URL(string: "http://example.com/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
// Use the async variant of URLSession to make an HTTP POST request:
let (data, response) = try await URLSession.shared.upload(for: request, from: requestData)
Complete example:
struct LoginResponse: Decodable {
let id: String
let name: String
}
func login(_ username: String, _ password: String) async throws -> LoginResponse {
struct RequestData: Encodable {
let username: String
let password: String
}
// Encode data to JSON to send in the POST request body:
let encoder = JSONEncoder()
let requestData = try encoder.encode(RequestData(username: username, password: password))
// Form the POST request:
let url = URL(string: "http://example.com/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
// Use the async variant of URLSession to make an HTTP POST request:
let (data, response) = try await URLSession.shared.upload(for: request, from: requestData)
print("HTTPURLResponse:", response)
print("The response body is:", String(decoding: data, as: UTF8.self))
// Parse the JSON response:
return try JSONDecoder().decode(LoginResponse.self, from: data)
}
Usage
You must call it in an async context (so you can await it). One way is using a Task:
Task {
do {
let loginResponse = try await login("user1", "mypassword")
print("Login successful for user with id:", loginResponse.id)
} catch {
print(error)
}
}
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData
// create post request
let url = NSURL(string: "http://httpbin.org/post")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData as Data
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
print("Result",result!)
} catch {
print("Error -> \(error)")
}
}
task.resume()
var request = URLRequest(url: URL(string: "your URL")!)
request.httpMethod = "POST"
let postString = String(format: "email=%#&lang=%#", arguments: [txt_emailVirify.text!, language!])
print(postString)
emailString = txt_emailVirify.text!
request.httpBody = postString.data(using: .utf8)
request.addValue("delta141forceSEAL8PARA9MARCOSBRAHMOS", forHTTPHeaderField: "Authorization")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil
else
{
print("error=\(String(describing: error))")
return
}
do
{
let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
print(dictionary)
let status = dictionary.value(forKey: "status") as! String
let sts = Int(status)
DispatchQueue.main.async()
{
if sts == 200
{
print(dictionary)
}
else
{
self.alertMessageOk(title: self.Alert!, message: dictionary.value(forKey: "message") as! String)
}
}
}
catch
{
print(error)
}
}
task.resume()
func function()
{
var parameters = [String:String]()
let apiToken = "Bearer \(ApiUtillity.sharedInstance.getUserData(key: "vAuthToken"))"
let headers = ["Vauthtoken":apiToken]
parameters = ["firstname":name,"lastname":last_name,"mobile":mobile_number,"email":emails_Address]
Alamofire.request(ApiUtillity.sharedInstance.API(Join: "user/edit_profile"), method: .post, parameters: parameters, encoding: URLEncoding.default,headers:headers).responseJSON { response in
debugPrint(response)
if let json = response.result.value {
let dict:NSDictionary = (json as? NSDictionary)!
print(dict)
// print(response)
let StatusCode = dict.value(forKey: "status") as! Int
if StatusCode==200
{
ApiUtillity.sharedInstance.dismissSVProgressHUDWithSuccess(success: "Success")
let UserData = dict.value(forKey: "data") as! NSDictionary
print(UserData)
}
else if StatusCode==401
{
let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
let ErrorMessage = ErrorDic.value(forKey: "error") as! String
}
else
{
let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
let ErrorMessage = ErrorDic.value(forKey: "error") as! String
}
}
else
{
ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: "Something went wrong")
}
}

How to POST JSON data using NSURLSession in swift

I am stuck with the below code. How do I set the param and in post method?
let params:[String:Any] = [
"email" : usr,
"userPwd" : pwdCode]
let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = params<what should do for Json parameter>
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if error {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
}
task.resume()
if I understand the question correctly
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
"email" : usr,
"userPwd" : pwdCode ]
let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
println(result)
}
task.resume()
I would suggest using AFNetworking. See for example, Posting JSON data using AFNetworking 2.0.
This is how you can set parameters and send a POST request, easy approach using Alamofire.
Swift 2.2
let URL = NSURL(string: "https://SOME_URL/web.send.json")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"
let parameters = ["api_key": "______", "email_details": ["fromname": "______", "subject": "this is test email subject", "from": "support#apple.com", "content": "<p> hi, this is a test email sent via Pepipost JSON API.</p>"], "recipients": ["_________"]]
do {
mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
// No-op
}
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(mutableURLRequest)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}