我有一个像这样的 NSString
:
http://www.
但我想将其转换为:
http%3A%2F%2Fwww.
我该怎么做?
最佳答案
要转义你想要的字符需要更多的工作。
示例代码
iOS7 and above:
NSString *unescaped = @"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(@"escapedString: %@", escapedString);
NSLog 输出:
escapedString: http%3A%2F%2Fwww
以下是有用的 URL 编码字符集:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
创建一个结合以上所有内容的字符集:
NSCharacterSet *URLCombinedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" \"#%/:<>?@[\\]^`{|}"] invertedSet];
创建一个 Base64
Base64字符集的情况下:
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"/+=\n"] invertedSet];
For Swift 3.0:
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
For Swift 2.x:
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
注意:stringByAddingPercentEncodingWithAllowedCharacters
也会对需要编码的 UTF-8 字符进行编码。
Pre iOS7 use Core Foundation
Using Core Foundation With ARC:
NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef) unescaped,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]\" "),
kCFStringEncodingUTF8));
在没有 ARC 的情况下使用 Core Foundation:
NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unescaped,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]\" "),
kCFStringEncodingUTF8);
注意:-stringByAddingPercentEscapesUsingEncoding
不会产生正确的编码,在这种情况下,它不会对返回相同字符串的任何内容进行编码。
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
编码 14 个字符:
`#%^{}[]|\"<> plus the space character as percent escaped.
测试字符串:
" `~!@#$%^&*()_+-={}[]|\\:;\"'<,>.?/AZaz"
编码字符串:
"%20%60~!@%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"
注意:请考虑这组字符是否满足您的需求,如果不能根据需要进行更改。
RFC 3986 需要编码的字符(% 添加,因为它是编码前缀字符):
"!#$&'()*+,/:;=?@[]%"
一些“未保留字符”被额外编码:
"\n\r \"%-.<>\^_`{|}~"
关于ios - Objective-C 和 Swift URL 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086584/