1

The following code is working perfectly for a simple http request. However I cant find a way of adding a payload or body string in Swift 3? and previous versions are depreciated

  func jsonParser(urlString: String, completionHandler: @escaping (_ data: NSDictionary) -> Void) -> Void
{
    let urlPath = urlString
    guard let endpoint = URL(string: urlPath) else {
        print("Error creating endpoint")
        return
    }

    URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData

            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }
            completionHandler(json)
        } catch let error as JSONError {
            print(error.rawValue)

        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()

}
shallowThought
  • 19,212
  • 9
  • 65
  • 112
ThundercatChris
  • 481
  • 6
  • 25

1 Answers1

8

You need to use URLRequest for that and then make call with that request.

var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
let postString = "postDataKey=value"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    do {
        guard let data = data else {
            throw JSONError.NoData

        }
        guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
            throw JSONError.ConversionFailed
        }
        completionHandler(json)
    } catch let error as JSONError {
        print(error.rawValue)

    } catch let error as NSError {
        print(error.debugDescription)
    }
}
task.resume()
Nirav D
  • 71,513
  • 12
  • 161
  • 183