I would like to get the percent encoded string for these specific letters, how to do that in objective-c?
Reserved characters after percent-encoding
! * ' ( ) ; : @ & = + $ , / ? # [ ]
%21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D
Please test with this string and see if it do work:
myURL = @"someurl/somecontent"
I would like the string to look like:
myEncodedURL = @"someurl%2Fsomecontent"
I tried with the stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding already but it does not work, the result is still the same as the original string. Please advice.
I’ve found that both
stringByAddingPercentEscapesUsingEncoding:andCFURLCreateStringByAddingPercentEscapes()are inadequate. TheNSStringmethod misses quite a few characters, and the CF function only lets you say which (specific) characters you want to escape. The proper specification is to escape all characters except a small set.To fix this, I created an
NSStringcategory method to properly encode a string. It will percent encoding everything EXCEPT[a-zA-Z0-9.-_~]and will also encode spaces as+(according to this specification). It will also properly handle encoding unicode characters.