11

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":"test@gmail.com"
}

Here is my code for this task

let dict = ["Email": "test@gmail.com", "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?

Vah.Sah
  • 522
  • 1
  • 6
  • 21
  • 1
    What's the result of `print(response)` and `print(json)`? – Eric Aya Nov 18 '16 at 12:17
  • the result of print(response) is Optional( { URL: http://xxxxxxxxx.net/api/Login } { status code: 415, headers { "Content-Length" = 0; Date = "Fri, 18 Nov 2016 12:20:21 GMT"; Server = "Microsoft-IIS/8.0"; "Set-Cookie" = "ARRAffinity=173cb9da56ba660395def768bf42f0686b2eba6731b99a6d8f2d08471ce133ed;Path=/;Domain=plubmeradmin.azurewebsites.net"; "X-Powered-By" = "ASP.NET"; } }) but print(json) is empty – Vah.Sah Nov 18 '16 at 12:21
  • You have your answer: `"Content-Length" = 0`. The data given by the server is empty. Also, have a look at [this Q&A](http://stackoverflow.com/questions/22566433/http-415-unsupported-media-type-error-with-json). – Eric Aya Nov 18 '16 at 12:23
  • thanks, but i still cannot understand what can be the reason of this. May be I'm doing wrong http request? – Vah.Sah Nov 18 '16 at 12:28
  • try with this https://stackoverflow.com/a/45304645/5437576 – User558 Jul 25 '17 at 13:23

1 Answers1

19

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!

Sahil Mahajan
  • 3,922
  • 2
  • 29
  • 43