目标-C和SWIFT URL编码

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (21)

我有一个NSString就像这样:

http://www.

但我想把它转换成:

http%3A%2F%2Fwww.

我该怎么做?

提问于
用户回答回答于

要想摆脱你想要的角色,需要做一些更多的工作。

示例代码

iOS 7及以上:

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

NSlog产出:

转义字符串:http%3A%2F%2Fwww

以下是有用的URL编码字符集:

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

创建一个综合了上述所有内容的字符集:

NSCharacterSet *URLCombinedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" \"#%/:<>?@[\\]^`{|}"] invertedSet];

创建base 64

就base 64字符集而言:

NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"/+=\n"] invertedSet];

SWIFT 3.0:

var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)

SWIFT 2.x:

var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())

注:stringByAddingPercentEncodingWithAllowedCharacters还将编码需要编码的UTF-8字符.

Pre iOS 7使用核心基础 将核心基础与ARC结合:undefined

NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
    NULL,
   (__bridge CFStringRef) unescaped,
    NULL,
    CFSTR("!*'();:@&=+$,/?%#[]\" "),
    kCFStringEncodingUTF8));

使用没有ARC的核心基础:

NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
   (CFStringRef)unescaped,
    NULL,
    CFSTR("!*'();:@&=+$,/?%#[]\" "),
    kCFStringEncodingUTF8);

注:-stringByAddingPercentEscapesUsingEncoding不会产生正确的编码,在这种情况下,它不会对任何返回相同字符串的内容进行编码。

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding编码14个字符:

#%^{}[]\“<>加上%转义的空格字符。undefined

测试串:

" `~!@#$%^&*()_+-={}[]|\\:;\"'<,>.?/AZaz"  

编码字符串:

"%20%60~!@%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"  

注意:考虑这组字符是否满足您的需要,如果没有根据需要更改它们。

需要编码的RFC 3986字符(%添加,因为它是编码前缀字符):

“#$&‘()*+,/:;=?@[]%“

一些“无保留字符”被额外编码:

“n”%-<>_{}~“

用户回答回答于

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
           (CFStringRef)self,
           NULL,
           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
           CFStringConvertNSStringEncodingToEncoding(encoding));
}

扫码关注云+社区