SHINTO JOSEPH
SHINTO JOSEPH

Reputation: 387

Unable to post parameters in post request ios swift

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()

Upvotes: 0

Views: 1044

Answers (3)

Abu Ul Hassan
Abu Ul Hassan

Reputation: 1396

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)
    }

Upvotes: 0

Matic Oblak
Matic Oblak

Reputation: 16774

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.

Upvotes: 1

Sruthi C S
Sruthi C S

Reputation: 129

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()

}

Upvotes: 2

Related Questions