Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

{ 
 "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?

like image 650
Vah.Sah Avatar asked Nov 18 '16 12:11

Vah.Sah


1 Answers

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!

like image 72
Sahil Mahajan Avatar answered Oct 24 '22 13:10

Sahil Mahajan