URLRequest POST doesn't work in Swift 5. There may be a problem with the server?

    let parametrs = ["word": newWord.word, "translate": newWord.translate , "studied" :newWord.studied] as [String : Any]

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parametrs, options: []) else { return }
    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response
        {
            print(response)
        }
        print(parametrs)
        guard let data = data else { return }
        do
        {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        }
        catch
        {
            print(error)
        }
    }.resume()

I think the problem is server related

NSHTTPURLResponse: 0x60000029d240

{ URL: http://pavlo-tymoshchuk-inc.right-k-left.com/wordList.json } { Status Code: 200, Headers { "Accept-Ranges" = ( bytes ); Connection = ( "Upgrade, Keep-Alive" ); "Content-Length" = ( 6689 ); "Content-Type" = ( "application/json" ); Date = ( "Fri, 07 Feb 2020 00:21:32 GMT" ); "Keep-Alive" = ( "timeout=15, max=100" ); "Last-Modified" = ( "Thu, 06 Feb 2020 22:55:22 GMT" ); Server = ( Apache ); Upgrade = ( "h2,h2c" ); } } ["word": "aaa", "translate": ["aaa"], "studied": false]

Upvotes: 0

Views: 296

Answers (1)

nine stones
nine stones

Reputation: 3438

Nothing wrong here.

  • Status 200
  • code doesn’t test for error but I bet it’s nil
  • Print of response is what you should expect
  • Print JSON prints a json object.

You should be happy. Or What would you expect?

Upvotes: 0

Related Questions