Created
December 18, 2017 16:17
-
-
Save Winchariot/3a736144a3c0df5579a4ab0f2a67801e to your computer and use it in GitHub Desktop.
Encode String for URL param or request body
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
//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