In iOS8 and prior I can use:
NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
in iOS9 stringByAddingPercentEscapesUsingEncoding
has been replaced with stringByAddingPercentEncodingWithAllowedCharacters
:
NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
and my question is: where to find needed NSCharacterSet
(NSUTF8StringEncoding
) for proper replacement of stringByAddingPercentEscapesUsingEncoding
?
Objective-C
this code work for me :
The deprecation message says (emphasis mine):
So you only need to supply an adequate
NSCharacterSet
as argument. Luckily, for URLs there's a very handy class method calledURLHostAllowedCharacterSet
that you can use like this:Update for Swift 3 -- the method becomes the static property
urlHostAllowed
:Be aware, though, that:
URLHostAllowedCharacterSet
is NOT WORKING FOR ME. I useURLFragmentAllowedCharacterSet
instead.OBJECTIVE -C
SWIFT - 4
The following are useful (inverted) character sets:
For Objective-C:
where to find set for NSUTF8StringEncoding?
There are predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to
-stringByAddingPercentEncodingWithAllowedCharacters:
.The deprecation message says (emphasis mine):
So you only need to supply an adequate
NSCharacterSet
as argument. Luckily, for URLs there's a very handy class method calledURLHostAllowedCharacterSet
that you can use like this:Be aware, though, that:
It means that you are not supposed to encode the
https://xpto.example.com/path/subpath
of the url, but only what goes after the?
.Supposed, because there are use-cases for doing it in cases like:
Where
xxxxx
is a fully encoded URL.For Swift 3.0
You can use
urlHostAllowed
characterSet.