I can\'t figure out how to properly send POST parameters.
My Swift 3:
let parameters = [\"name\": \"thom\", \"password\": \"12345\"] as Dictionary&l
You want to percent-escape the request into a x-www-form-urlencoded
request, like so:
let parameters = ["name": "thom", "password": "12345"]
let url = URL(string: "https://mywebsite.com/test.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.updateHttpBody(with: parameters)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("\(error)")
return
}
// handle response here
}
task.resume()
Where
extension URLRequest {
/// Populate the `httpBody` of `application/x-www-form-urlencoded` request.
///
/// - parameter parameters: A dictionary of keys and values to be added to the request
mutating func updateHttpBody(with parameters: [String : String]) {
let parameterArray = parameters.map { (key, value) -> String in
return "\(key.addingPercentEncodingForQueryValue()!)=\(value.addingPercentEncodingForQueryValue()!)"
}
httpBody = parameterArray.joined(separator: "&").data(using: .utf8)
}
}
extension String {
/// Percent escape value to be added to a HTTP request
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "*".
/// This will also replace spaces with the "+" character as outlined in the application/x-www-form-urlencoded spec:
///
/// http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
///
/// - returns: Return percent escaped string.
func addingPercentEncodingForQueryValue() -> String? {
let generalDelimitersToEncode = ":#[]@?/"
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return addingPercentEncoding(withAllowedCharacters: allowed)?.replacingOccurrences(of: " ", with: "+")
}
}