In the Message Section people are able to post a message. This section of my appliaction (Swift) uses a php script! How am i able to send the content of those Textfields to the Server using the Post Method?
How to send the Content of multiple TextFields to a PHP Script using the Post method?
That depends on how the HTTP server expects the
POST body data to be formatted:
If it’s expecting JSON data, you’d use
to serialise some native values to aJSONSerialization
value you can use for the HTTP request’s body.DataIf it’s expecting
, there’s no iOS API to building the required body data. If you can either use a third-party library to do this or simply write the code yourself.application/x-www-form-urlencodedNote Pasted in below is the code I use to do this.
And so on
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"/// Encodings the key-values pairs in `application/x-www-form-urlencoded` format.
///
/// The only specification for this encoding is the [Forms][spec] section of the
/// *HTML 4.01 Specification*. That leaves a lot to be desired. For example:
///
/// * The rules about what characters should be percent encoded are murky
///
/// * It doesn't mention UTF-8, although many clients do use UTF-8
///
/// [spec]: <http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4>
///
/// - parameter formDataSet: An array of key-values pairs
///
/// - returns: The returning string.
func urlEncoded(formDataSet: [(String, String)]) -> String {
return formDataSet.map { (key, value) in
return escape(key) + "=" + escape(value)
}.joined(separator: "&")
}
/// Returns a string escaped for `application/x-www-form-urlencoded` encoding.
///
/// - parameter str: The string to encode.
///
/// - returns: The encoded string.
private func escape(_ str: String) -> String {
// Convert LF to CR LF, then
// Percent encoding anything that's not allow (this implies UTF-8), then
// Convert " " to "+".
//
// Note: We worry about `addingPercentEncoding(withAllowedCharacters:)` returning nil
// because that can only happen if the string is malformed (specifically, if it somehow
// managed to be UTF-16 encoded with surrogate problems) <rdar://problem/28470337>.
return str.replacingOccurrences(of: "\n", with: "\r\n")
.addingPercentEncoding(withAllowedCharacters: sAllowedCharacters)!
.replacingOccurrences(of: " ", with: "+")
}
/// The characters that are don't need to be percent encoded in an `application/x-www-form-urlencoded` value.
private let sAllowedCharacters: CharacterSet = {
// Start with `CharacterSet.urlQueryAllowed` then add " " (it's converted to "+" later)
// and remove "+" (it has to be percent encoded to prevent a conflict with " ").
var allowed = CharacterSet.urlQueryAllowed
allowed.insert(" ")
allowed.remove("+")
return allowed
}()