Avoid using the deprecated methods
CFURLCreateStringByAddingPercentEscapes
and
stringByAddingPercentEscapesUsingEncoding
.
Although Dave's answer is on the right track, it lacks specificity.
Instead of using
NSCharacterSet.URLQueryAllowedCharacterSet
, manually create a character set based on the documentation for
encodeURIComponent()
:
A–Z a–z 0–9 - _ . ! ~ * ' ( )
Here is an improved solution:
+ (NSString *)encodeURIComponent:(NSString *)uriComponent {
NSString *allowedChars = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"-_.!~*'()";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:allowedChars];
return [uriComponent stringByAddingPercentEncodingWithAllowedCharacters:charSet];
}
+ (NSString *)decodeURIComponent:(NSString *)uriComponent {
return [uriComponent stringByRemovingPercentEncoding];
}