Mike Henderson Mike Henderson - 6 months ago 18
Swift Question

Encode URL with http://

I know how to encode a string in URL format (the smiley face is intentional):

let str = "www.mywebsite.com/

Answer

: is not a legal character in the path part of an URL. You percent-encoded everything not in URLPathAllowedCharacterSet, so it shouldn't be surprising that the : was encoded.

Each part of an URL has different encoding rules. iOS can't correctly encode an URL until it knows what goes in what part, and it can't do that from an unencoded string (since it'd have to parse it first, and it can't parse it because it's not correctly encoded yet). In some systems (including older versions of iOS), it would use various heuristics that assumed "well, I guess you probably meant..." rather than actually following the URL-encoding rules. This was convenient common cases, while mis-encoding less common, but legal, cases (especially involving non-http URLs and non-Latin URLs). iOS now follows the rules, so things encode consistently, but it means you need to actually think about URLs and not just throw random stuff at the system and hope it figures it out.

The best way to do this (if you have to compute this stuff dynamically) is with NSURLComponents:

let url = NSURLComponents()
url.scheme = "http"
url.host = "www.mywebsite.com"
url.path = "/