Sending JSON POST request in Swift3

Vah.Sah picture Vah.Sah · Nov 18, 2016 · Viewed 20.3k times · Source

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

{ 
 "Password":"123456",   
 "Email":"[email protected]"
}

Here is my code for this task

let dict = ["Email": "[email protected]", "Password":"123456"] as [String: Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {


    let url = NSURL(string: "http://xxxxxxxxx.net/api/Login")!
    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{
           print(error?.localizedDescription)
           return
        }

        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)")
                   print(parseJSON)
                   }
            } catch let error as NSError {
                 print(error)
            }        
       }          
     task.resume()
    }

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

Sahil Mahajan picture Sahil Mahajan · Nov 18, 2016

Try two things:

First :

jsonData = try? JSONSerialization.data(withJSONObject: 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!