0

I'm trying to send these parameters as a post request to the URL but the parameters are not getting sent. I don't know whether is URLSession configuration issue. Can anyone check and solve the issue?

import UIKit

let json: [String: Any] = [
    "set_id" : "20",
    "user_id" :  "30",
    "type" : "contact",
    "contact_name" : "shinto"
]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

var str = String(data: jsonData!, encoding: .utf8)

let url = URL(string: "****.php")!
var request = URLRequest(url: url)

request.httpMethod = "Post"
request.httpBody = str!.data(using: .utf8)

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {

  (data, response, error) in
    if let data = data {
      if let postResponse = String(data: data, encoding: .utf8) {
        print(postResponse)
      }
    }

}
task.resume()
Jarvis The Avenger
  • 2,750
  • 1
  • 19
  • 37
SHINTO JOSEPH
  • 377
  • 4
  • 17
  • 2
    `request.httpBody = str!.data(using: .utf8)` Why not doing `request.httpBody = jsonData` directly? Now how do you know that "the parameters are not getting send"? Also, `request.httpMethod = "Post"` use `POST` (all uppercase?) – Larme Apr 29 '19 at 10:36
  • @Larme not working bro – SHINTO JOSEPH Apr 29 '19 at 10:41
  • let jsonData = try? JSONSerialization.data(withJSONObject: userID, options:.prettyPrinted) as Data. Now set request.httpBody = jsonData – Friend Apr 29 '19 at 10:59
  • have you mentioned `Content-Type` as json in header ? – Fahadsk Apr 29 '19 at 11:01
  • Yes, some customFields i add var urlRequest = URLRequest(url: getOEMurl!) urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.setValue(String(format:"%f",(userIdJson?.count)!), forHTTPHeaderField: "Content-Length") – Friend Apr 29 '19 at 11:12
  • Can you make it work in Postman? Does it work there? – Larme Apr 29 '19 at 13:18

3 Answers3

2

Check with this:

      func post method(){
      let headers = [
        "Content-Type": "application/json",
        "cache-control": "no-cache"]


    let parameters = ["set_id" : "20",
                      "user_id" :  "30",
                      "type" : "contact",
                      "contact_name" : "shinto"] as [String : Any]



    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

    let url = URL(string: "****.php")!
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as! Data

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        }
        guard let httpresponse = response as? HTTPURLResponse,
            (200...299).contains(httpresponse.statusCode) else {
                print ("server error")
                return
        }


        if let mimeType = response?.mimeType,
            mimeType == "application/json",
            let data = data,
            let dataString = String(data: data, encoding: .utf8) {
            print ("got data: \(dataString)")

     }
     }
    })

    dataTask.resume()

}
Sruthi C S
  • 131
  • 6
1

I used an online service called RequestBin to inspect your request and data seem to be sent correctly. I only did minor modifications as already mentioned in the comment.

This was the resulting code:

let json: [String: Any] = [
    "set_id" : "20",
    "user_id" :  "30",
    "type" : "contact",
    "contact_name" : "shinto"
]
let jsonData = try! JSONSerialization.data(withJSONObject: json)

let url = URL(string: "http://requestbin.fullcontact.com/***")! // Was "using"
var request = URLRequest(url: url)

request.httpMethod = "POST" // Was "Post"
request.httpBody = jsonData // Was utf8 string representation

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
    (data, response, error) in
    if let data = data {
        if let postResponse = String(data: data, encoding: .utf8) {
            print(postResponse)
        }
    }

}
task.resume()

You can check inspected result using this service. You simply create a new URL and use it in your request. After you have successfully sent the request all you do is reload the page to inspect your request.

Note that these are "http" requests so you need to allow arbitrary loads.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
0

You may set your request like following and change content type according to your need

import UIKit    
let json: [String: Any]? = [
    "set_id" : "20",
    "user_id" :  "30",
    "type" : "contact",
    "contact_name" : "shinto"
]
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
if let parameters = json
{
    self.makeParamterString(request: request, parameterDic: parameters)
}

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {

  (data, response, error) in
    if let data = data {
      if let postResponse = String(data: data, encoding: .utf8) {
        print(postResponse)
      }
    }

}
task.resume()
     static  func makeParamterString(request:NSMutableURLRequest, parameterDic:[String:AnyObject])
    {
        let _ =  NSCharacterSet(charactersIn:"=\"#%/<>?@\\^`{|}").inverted
        var dataString = String()
        for (key, value) in parameterDic {
            dataString = (dataString as String) + ("&\(key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)=\(value)")
        }
        dataString = dataString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
        request.httpBody = dataString.data(using: String.Encoding.utf8)
    }
Abu Ul Hassan
  • 1,340
  • 11
  • 28