Search code examples
objective-cnsstringios9nsurlbackslash

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 = @"http://domain.com/interface/?end=imember";
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:

URLUserAllowedCharacterSet
URLPasswordAllowedCharacterSet
URLHostAllowedCharacterSet
URLPathAllowedCharacterSet
URLQueryAllowedCharacterSet
URLFragmentAllowedCharacterSet

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

EDIT:

This is what the url should look like:

http://domain.com/interface/?end=imember&client_key=KOB3N6KX9JXF2MRPO5U.BRFYM7TYVE\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=

Solution

  • 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 = @"http://domain.com/interface/?end=imember"];
    NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
    NSLog(@"escapedString: %@", escapedString);
    

    URL Encoding Character Sets are

    URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
    URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
    URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
    URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
    URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
    URLUserAllowedCharacterSet      "#%/:<>?@[\]^`