Skip to content

Instantly share code, notes, and snippets.

@annidy
Forked from Winchariot/String+Extensions.swift
Created February 3, 2023 15: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 annidy/efeda48f2ad23056093063003f2a21c8 to your computer and use it in GitHub Desktop.
Save annidy/efeda48f2ad23056093063003f2a21c8 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