Search code examples
postswift5form-data

How to send POST request with httpBody form-data in Swift 5?


I want to send POST request in form like this

I tried the code below. But, I was not successful.

    let url = URL(string: "https://www.blablabla.com")!

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let json: [String: Any] = ["test":"info"]

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

    if let JSONString = String(data: jsonData!, encoding: String.Encoding.utf8) {
        let req = "{TestRequest=" + JSONString + "}"
        // Also, I tried this: let req = "TestRequest=" + JSONString
        request.httpBody = req.data(using: String.Encoding.utf8)
    }

    URLSession.shared.dataTask(with: url) {(data, response, error) in
        do {
            // JSON Parsing

        } catch {
            // Show error message

        }
    }.resume()

I got this error:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.})))

When I try with Postman, it runs smoothly.


Solution

  • Sorry, I made a mistake on code. When I try the code below, I succeeded.

    let url = URL(string: "https://www.blablabla.com")!
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    
    let req = "TestRequest={\"test\":\"info\"}"
    request.httpBody = req.data(using: String.Encoding.utf8)
    URLSession.shared.dataTask(with: request) {(data, response, error) in
        do {
            // JSON Parsing
    
        } catch {
            // Show error message
    
        }
    }.resume()
    

    The main problem is to start the session with "url" instead of the "request".