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

}

1 Answer 1

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()
1
  • man you my hero, I searched for ages, but I only found how to do a JSON Post not a string post, thanks a lot! Nov 10, 2019 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.