Skip to content

Instantly share code, notes, and snippets.

@phausler
Created July 10, 2017 21:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phausler/e945f1b9c6486ff9a990487261fdeab4 to your computer and use it in GitHub Desktop.
Save phausler/e945f1b9c6486ff9a990487261fdeab4 to your computer and use it in GitHub Desktop.
var inStr:String
var outStr:String
// bad IP-literal (there are no square brackets around the address)
inStr = "2606:2800:220:1:248:1893:25c8:1946"
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
// outStr = "2606%3A2800%3A220%3A1%3A248%3A1893%3A25c8%3A1946"
// valid IP-literal (there are square brackets around the address)
inStr = "[2606:2800:220:1:248:1893:25c8:1946]"
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
// outStr = "[2606:2800:220:1:248:1893:25c8:1946]"
// valid IPv4address (all decimal digits and periods)
inStr = "93.184.216.34";
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
// outStr = "93.184.216.34"
// reg-name with no characters that need to be percent encoded
inStr = "www.example.com";
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
// outStr = "www.example.com"
// reg-name with characters that need to be percent encoded
inStr = "💩.la";
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
// outStr = "%F0%9F%92%A9.la"
// the first ':' does not have to be percent-encoded because it is before the first '/'
inStr = "/foo:bar/foo:bar";
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
// outStr = "/foo:bar/foo:bar"
// the first ':' has to be percent-encoded because it is before the first '/'
inStr = "foo:bar/foo:bar";
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
// outStr = "foo%3Abar/foo:bar"
// the ';' has to be percent-encoded for backwards compatibility with CFURL and NSURL which parse to an older deprecated standard that included a parameter component starting at the first ';' character
inStr = "a;b";
outStr = inStr.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
// outStr = "a%3Bb"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment