You need to percent-escape the httpBody
data:
Manually build the body
let parameters = [
"customer": "John Smith",
"address": "123 Fake St., Some City"
]
let httpBody = parameters.map {
$0 + "=" + $1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
.joined(separator: "&")
.data(using: .utf8)!
While the parameter's name can contain special characters, this is extremely rare. If your API happens to use that, escape $0
in the closure as well.
Using URLComponents
var components = URLComponents()
components.queryItems = [
URLQueryItem(name:"customer", value: "John Smith"),
URLQueryItem(name:"address", value: "123 Fake St., Some City")
]
// Drop the `&` character in front of the query string
let httpBody = components.string!.dropFirst().data(using: .utf8)!
URLComponents
will automatically encode any special character in both the parameter's name and value. This also guarantee the order of the parameters in the POST data, which is important for some API calls.