Objective-C和Swift URL编码

Objective-C和Swift URL编码,第1张

Objective-C和Swift URL编码

逃避想要的角色还需要做更多的工作。

范例程式码

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字符进行编码。

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:NSUTF8StringEncoding
编码14个字符:

`#%^ {} [] | “ <>加上转义百分比的空格字符。

testString:

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

enpreString:

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

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

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

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

一些“未保留的字符”还被编码:

“ n r ”%-。<> ^ _`{|}〜“



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642151.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存