Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/1ecf5c7f4bf4d78a8cbc to your computer and use it in GitHub Desktop.
Save robertmryan/1ecf5c7f4bf4d78a8cbc to your computer and use it in GitHub Desktop.
An example of populating a HTTPBody of NSMutableURLRequest for `application/x-www-form-urlencoded` request in response to http://stackoverflow.com/questions/28008874/post-with-swift-and-api/28009796#comment44430194_28009796
extension NSMutableURLRequest {
/// Populate the HTTPBody of `application/x-www-form-urlencoded` request
///
/// :param: contentMap A dictionary of keys and values to be added to the request
func setBodyContent(contentMap: [String : String]) {
let parameters = map(contentMap) { (key, value) -> String in
return "\(key)=\(value.stringByAddingPercentEscapesForQueryValue()!)"
}
HTTPBody = "&".join(parameters).dataUsingEncoding(NSUTF8StringEncoding)
}
}
extension String {
/// Percent escape value to be added to a URL query value as specified in RFC 3986
///
/// This percent-escapes all characters except the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Return precent escaped string.
func stringByAddingPercentEscapesForQueryValue() -> String? {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._~")
return stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment