我想获得这些特定字母的百分比编码字符串,如何在objective-c中实现这一点?

Reserved characters after percent-encoding
!   *   '   (   )   ;   :   @   &   =   +   $   ,   /   ?   #   [   ]
%21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D

Percent-encoding wiki

请使用此字符串进行测试,看看它是否有效:

myURL = @"someurl/somecontent"

我希望字符串看起来像:

myEncodedURL = @"someurl%2Fsomecontent"

我已经try 了stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding,但它不起作用,结果仍然与原始字符串相同.请给我一些建议.

推荐答案

我发现stringByAddingPercentEscapesUsingEncoding:CFURLCreateStringByAddingPercentEscapes()都不够.NSString方法漏掉了很多字符,CF函数只允许您说出要转义的(特定)字符.正确的规范是转义除小字符集以外的所有字符.

为了解决这个问题,我创建了NSString category方法来正确编码字符串.它将对除[a-zA-Z0-9.-_~]之外的所有内容进行百分比编码,并将空格编码为+(根据this specification).它还将正确处理unicode字符的编码.

- (NSString *) URLEncodedString_ch {
    NSMutableString * output = [NSMutableString string];
    const unsigned char * source = (const unsigned char *)[self UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

Objective-c相关问答推荐

UITableView/UITableViewCell 点击事件响应?

Objective-C 和 Cocoa 有什么区别?

表达式不可分配 - 将浮点数分配为 Xcode 中其他两个浮点数的总和时出现问题?

XCTAssert 和 XCTAssertTrue 有什么区别?

#if 和 #ifdef Objective-C 预处理器宏有什么区别?

以编程方式调用情节提要场景(无需转场)?

静态 NSString 使用与内联 NSString 常量

如何将当前方法的名称或签名放入 NSString?

避免NSArray 在被枚举时发生Mutations

实现 -hash / -isEqual: / -isEqualTo...: 用于 Objective-C 集合

未找到 RKObjectMapping.h

Lipo错误!!无法打开输入文件

Cocoa 的依赖注入框架?

如何推送两个视图控制器但只为第二个设置动画过渡?

立即检测 iOS 方向变化

IOHIDFamily 的神秘控制台错误

NSAssert vs assert :您使用哪个,何时使用?

如何以编程方式在 UINavigationController 中按下返回按钮

iOS ScrollView 需要约束 y 位置或高度

AVAudioPlayer 不播放任何声音