我有一个NSString这样的:
NSString
http://www.
但我想将其转换为:
http%3A%2F%2Fwww.
我怎样才能做到这一点?
逃避想要的角色还需要做更多的工作。
范例程式码
iOS7及以上:
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];
对于Swift 3.0:
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
对于Swift 2.x:
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
注意:stringByAddingPercentEncodingWithAllowedCharacters还将对需要编码的UTF-8字符进行编码。
stringByAddingPercentEncodingWithAllowedCharacters
iOS7之前的版本 将Core Foundation与ARC一起使用Core Foundation:
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
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding 编码14个字符:
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
`#%^ {} [] | \“ <>加上转义百分比的空格字符。
testString:
" `~!@#$%^&*()_+-={}[]|\\:;\"'<,>.?/AZaz"
encodeString:
"%20%60~!@%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"
注意:请考虑这组字符是否满足您的需求,如果没有根据需要进行更改。
需要编码的RFC 3986字符(已添加%,因为它是编码前缀字符):
“!#$&’()* +,/:; =?@ []%”
一些“未保留的字符”还被编码:
“ \ n \ r \”%-。<> \ ^ _`{|}〜“