Swift PUT and PATCH requests not sending httpBody

coding software

Hey everyone, this will be a quick one.

I'm finally coding a Swift iOS app to interface with my Rails app and I'm now at the point where I'm starting to implement PUT or PATCH requests for my record updates.

For my requests, I have a basic APIController that runs this code to build the request:

urlRequest = URLRequest(url: url) urlRequest.httpMethod = "PATCH" urlRequest.httpBody = bodyString.data(using: .utf8)

This method generally worked perfectly fine for my POST requests, but for some reason PUT and PATCH requests were not sending the httpBody.

Turns out, for PUT and PATCH you need to be explicit about the content type. Since I was using form urlEncoded data (so something that looks like "key=value&key=value&key=value" I just had to add this line:

urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

And then everything worked.

So final code looked like this:

urlRequest = URLRequest(url: url) urlRequest.httpMethod = "PATCH" urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = bodyString.data(using: .utf8)

Hope that helps out some peeps!

Casey Li
CEO & Founder, BiteSite