Vah.Sah Vah.Sah - 9 months ago 92
Swift Question

Sending JSON POST request in Swift3

In my app i'm trying to make http post request with json data. The following json must be transferred to api


Here is my code for this task

let dict = ["Email": "", "Password":"123456"] as [String: Any]
if let jsonData = try? dict, options: []) {

let url = NSURL(string: "")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"

request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{

do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

if let parseJSON = json {
let resultValue:String = parseJSON["success"] as! String;
print("result: \(resultValue)")
} catch let error as NSError {

I'm getting the following error

Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}

The response data is empty. What I'm doing wrong, or i have missed something in my code?

Answer Source

Try two things:

First :

jsonData = try? dict, options: .prettyPrinted)

then add logs if your data is converted into JSON. Convert your data into String and print the value.

Also add

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

before httpBody. Sometimes we have to tell server in our request that we are posting JSON data.

Hope this will help you!!

Happy Coding!