Skip to content

Instantly share code, notes, and snippets.

@Winchariot
Created December 18, 2017 16:17
Show Gist options
  • Save Winchariot/3a736144a3c0df5579a4ab0f2a67801e to your computer and use it in GitHub Desktop.
Save Winchariot/3a736144a3c0df5579a4ab0f2a67801e to your computer and use it in GitHub Desktop.
Encode String for URL param or request body
//Both implementations thanks to https://useyourloaf.com/blog/how-to-percent-encode-a-url-string/
//Upgraded/cleaned up for Swift 4
Extension String {
func percentEncodedForRFC3986() -> String? {
let unreserved = "-._~/?"
var allowed = CharacterSet.alphanumerics
allowed.insert(charactersIn: unreserved)
return self.addingPercentEncoding(withAllowedCharacters: allowed)
}
func x_www_form_urlencoded(encodeSpace: Bool = true) -> String? {
let unreserved = "*-._"
var allowed = CharacterSet.alphanumerics
allowed.insert(charactersIn: unreserved)
//encoding space is apparently optional
if encodeSpace == false {
allowed.insert(charactersIn: " ")
}
guard var encoded = self.addingPercentEncoding(withAllowedCharacters: allowed) else { return nil }
if encodeSpace {
encoded = encoded.replacingOccurrences(of: " ", with: "+")
}
return encoded
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment