ios - Objective-C 和 Swift URL 编码

我有一个像这样的 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 \"%-.<>\^_`{|}~"

https://stackoverflow.com/questions/8086584/

相关文章:

iphone - 什么是使 iOS 应用程序崩溃的可靠方法?

ios - 如何使 UIButton 文本对齐中心?使用 IB

iphone - 错误 : The service is invalid

objective-c - 关于iOS5 SDK中自动引用计数的一些问题

objective-c - Objective-C 中的 MD5 算法

objective-c - 如何在 UIScrollView 内的 UIWebView 上启用放大功

objective-c - 使用 NSLocalizedString 的最佳实践

ios - 如何在 UILabel 中嵌入小图标

iphone - 以编程方式选择 tableview 行

ios - 使用 glob 获取目录中的文件列表