Does NSURLSession automatically URL-encode the text of the URL? Or do you have to manually do it?
-
No, you have to escape them yourself. You should show us an example of the sort of URL (e.g. is it just a scheme, host, and path, or does it include parameters at the end in the form of `&foo=bar`) and we can help you further. – Rob Jan 12 '16 at 19:00
1 Answers
No, you need to use stringByAddingPercentEncodingWithAllowedCharacters:
to encode each part of the URL. See URLFragmentAllowedCharacterSet
, URLHostAllowedCharacterSet
, etc. for the correct characters to encode each piece of the URL.
(Note that none of this has anything to do with NSURLSession
, which requires an NSURL
already. It doesn't accept strings, so encoding is not its problem. The right question is whether NSURL
automatically escapes characters passed as a string.)
(Also be sure to read the comments below. While stringByAddingPercentEncodingWithAllowedCharacters:
will correctly encode each part of your URL, you may not be completely aware of what "correctly" means according to the RFCs. In particular, queries may require additional encoding if they include &
or +
.)

- 286,113
- 34
- 456
- 610
-
Agreed. And in some cases, even those predefined character sets are sometimes insufficient (e.g. when percent escaping the values added to a `GET` query, because `&` and `+` are allowed by all of those `URLxxx` character sets). – Rob Jan 12 '16 at 18:59
-
Right, since `&` and `+` aren't special characters in the *URL*. They're special characters in the x-www-form-urlencoded format which is a completely different thing, and only even applicable to certain schemes. Oh the twisty passages of how URLs are defined vs how people think they must work. In principle, you really should build up URLs from components rather than by parsing strings (so you can avoid most of these issues), but it's rare anyone does it that way. – Rob Napier Jan 12 '16 at 19:12
-
1Agreed on all counts. I just get frustrated where people suggest "just use `stringByAddingPercentEscapesUsingEncoding`" (or whatever), when the encoding problem is, more often than not, in the query, not in the hostname or path of the URL. The OP didn't say what he/she was really trying to do, so we can't be certain, tho. – Rob Jan 12 '16 at 19:29
-
1OS X 10.9 and iOS 7 introduced `NSURLComponents` to parse and construct URLs. It can handle the encoding stuff automatically. – vadian Jan 12 '16 at 20:16
-
@vadian - Yes, that's better, but you're still left escaping the query portion yourself. `NSURLQueryItem` lets `+` pass unescaped in query value, but that's wrong. It must be escaped within the query `application/x-www-form-urlencoded` requests. – Rob Jan 14 '16 at 22:05