0

Im making a POST request to the API. I have tested the API using Postman and another third party tool and Im getting a 200 response. But when I make a request from swift I get a 405 response (method not allowed) and an error message saying that "GET" request is not allowed even though clearly Im making a POST request.

I have checked the httpBody which definitely contains the data. I just can't figure out what I'm doing wrong here. Here is my code:

    let json : [Dictionary<String,Any>] = [["label" : "Misc", "ignored": true], ["label" : "Cash", "ignored": false]]
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = try? JSONSerialization.data(withJSONObject: json)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let response = response {
            print(response)
        }
    }

    task.resume()
iOSDev
  • 1
  • 1

1 Answers1

2

Try using

URLSession(configuration: URLSessionConfiguration.default)

instead of

URLSession.shared

I ran into the same problem and this worked for me.

Omkar
  • 3,040
  • 1
  • 22
  • 42