-2

Here I need to post data using PUT method to the server but i am unable to post it and it's working fine in postman. Is my json function was wrong if it is wrong can anyone help me how to implement this ?

func itemsIncrementingandDecrementingtocartDownloadJsonWithURL(itemsApi: String){
        print(itemsApi)
        let url = URL(string: itemsApi)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "PUT"
        let parameters : [String: Any] = ["cartItem":
            [
                "item_id": itemId!,
                "qty": quantity!,
                "quote_id": "\(self.key!)"
            ]
        ]
        print(parameters)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let session = URLSession(configuration:URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in

            if error != nil {

                //handle error
            }
            else {

                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("Parsed JSON: '\(jsonStr)'")
            }
        }
        dataTask.resume()
    }
Vamsi S
  • 269
  • 3
  • 16

2 Answers2

0

At first serialize the parameters to json string and add string to request http body.

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = postData as Data

This will help you.

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
0

Try add this.

let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
request.httpBody = data
Lumialxk
  • 6,239
  • 6
  • 24
  • 47