Skip to content

Instantly share code, notes, and snippets.

@soffes
Last active December 17, 2015 17:19
Show Gist options
  • Select an option

  • Save soffes/03861a2714881e008107 to your computer and use it in GitHub Desktop.

Select an option

Save soffes/03861a2714881e008107 to your computer and use it in GitHub Desktop.
import Foundation
let queryItems = [
NSURLQueryItem(name: "username", value: "so&ffes"),
NSURLQueryItem(name: "password", value: "123456")
]
func formEncode(queryItems: [NSURLQueryItem]) -> String {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._~")
return queryItems.flatMap { item -> String? in
guard var output = item.name.stringByAddingPercentEncodingWithAllowedCharacters(characterSet) else { return nil }
output += "="
if let value = item.value?.stringByAddingPercentEncodingWithAllowedCharacters(characterSet) {
output += value
}
return output
}.joinWithSeparator("&")
}
formEncode(queryItems) // username=so%26ffes&password=123456
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment