Last active
August 29, 2015 14:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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