Alexander Alexander - 1 year ago 188
Objective-C Question

NSURL: Escape Backslash using NSCharacterSet

This may be a duplicate question, but I have checked all over and can't find a working answer for iOS9. -stringByAddingPercentEscapesUsingEncoding has been deprecated. I need to use -stringByAddingPercentEncodingWithAllowedCharacters

Below is the string that needs the backslashes escaped so that the API can authenticate the session and return a response.

NSString *base = @"";
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *key = [@"&client_key=KOB3N6KX9JXF2MRPO5U.BRFYM7TYVE\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=" stringByAddingPercentEncodingWithAllowedCharacters:set];

The standard URL Character sets don't escape the backslashes, I have tried them all:


Please if someone could assist, I am rather new to development. Is it possible to create a custom allowed set which includes the backslash?


This is what the url should look like:\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=

Answer Source

The exact solution for you answer is below.I got it from Zaph's answer.That is the better answer than other answer.

NSString *unescaped = @""];
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(@"escapedString: %@", escapedString);

URL Encoding Character Sets are

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download