NSURL:使用 NSCharacterSet 转义反斜杠

NSURL: Escape Backslash using NSCharacterSet

这可能是一个重复的问题,但我已经检查了所有内容,但找不到 iOS9 的有效答案。 -stringByAddingPercentEscapesUsingEncoding 已被弃用。我需要使用 -stringByAddingPercentEncodingWithAllowedCharacters

下面是需要反斜杠转义的字符串,以便 API 可以验证会话和 return 响应。

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];

标准URL字符集不转义反斜杠,我都试过了:

URLUserAllowedCharacterSet
URLPasswordAllowedCharacterSet
URLHostAllowedCharacterSet
URLPathAllowedCharacterSet
URLQueryAllowedCharacterSet
URLFragmentAllowedCharacterSet

如果有人可以提供帮助,我是开发新手。是否可以创建包含反斜杠的自定义允许集?

编辑:

url 应该是这样的:

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

您的确切答案是 below.I 从 Zaph's answer 得到的。这是比其他答案更好的答案。

NSString *unescaped = @"http://domain.com/interface/?end=imember"];
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(@"escapedString: %@", escapedString);

URL编码字符集是

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