首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Objective-c iPhone percent编码字符串?

Objective-c iPhone percent编码字符串?
EN

Stack Overflow用户
提问于 2010-08-06 20:02:47
回答 7查看 49.7K关注 0票数 72

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

代码语言:javascript
复制
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

请使用此字符串进行测试,看看它是否可以工作:

代码语言:javascript
复制
myURL = @"someurl/somecontent"

我希望字符串看起来像这样:

代码语言:javascript
复制
myEncodedURL = @"someurl%2Fsomecontent"

我已经尝试了stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding,但它不起作用,结果仍然与原始字符串相同。敬请指教。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-08-07 01:20:25

我发现stringByAddingPercentEscapesUsingEncoding:CFURLCreateStringByAddingPercentEscapes()都不够用。NSString方法遗漏了相当多的字符,而CF函数只允许您说出要转义的(特定)字符。正确的规范是转义除一小部分之外的所有字符。

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

代码语言:javascript
复制
- (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;
}
票数 144
EN

Stack Overflow用户

发布于 2013-11-29 00:46:30

iOS 7SDK现在有了一个比stringByAddingPercentEscapesUsingEncoding更好的选择,它允许您指定除了某些允许的字符之外的所有字符都要进行转义。如果你将URL分成几个部分来构建,它会工作得很好:

代码语言:javascript
复制
NSString * unescapedQuery = [[NSString alloc] initWithFormat:@"?myparam=%d", numericParamValue];
NSString * escapedQuery = [unescapedQuery stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString * urlString = [[NSString alloc] initWithFormat:@"http://ExampleOnly.com/path.ext%@", escapedQuery];

虽然URL的其他部分很少是变量,但在NSURLUtilities类别中也有用于这些部分的常量:

代码语言:javascript
复制
[NSCharacterSet URLHostAllowedCharacterSet]
[NSCharacterSet URLUserAllowedCharacterSet]
[NSCharacterSet URLPasswordAllowedCharacterSet]
[NSCharacterSet URLPathAllowedCharacterSet]
[NSCharacterSet URLFragmentAllowedCharacterSet]

[NSCharacterSet URLQueryAllowedCharacterSet]包括URL的查询部分(以?开头,片段的#之前的部分,如果有)中允许的字符的所有,包括?&=字符,这些字符用于分隔参数名称和值。对于具有字母数字值的查询参数,用于构建查询字符串的变量的值中可能包含这些字符中的任何字符。在这种情况下,查询字符串的每个部分都需要转义,这只需要多做一点工作:

代码语言:javascript
复制
NSMutableCharacterSet * URLQueryPartAllowedCharacterSet; // possibly defined in class extension ...

// ... and built in init or on first use
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:@"&+=?"]; // %26, %3D, %3F

// then escape variables in the URL, such as values in the query and any fragment:
NSString * escapedValue = [anUnescapedValue stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSString * escapedFrag = [anUnescapedFrag stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSString * urlString = [[NSString alloc] initWithFormat:@"http://ExampleOnly.com/path.ext?myparam=%@#%@", escapedValue, escapedFrag];
NSURL * url = [[NSURL alloc] initWithString:urlString];

unescapedValue甚至可以是一个完整的URL,例如用于回调或重定向:

代码语言:javascript
复制
NSString * escapedCallbackParamValue = [anAlreadyEscapedCallbackURL stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSURL * callbackURL = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"http://ExampleOnly.com/path.ext?callback=%@", escapedCallbackParamValue]];

注意:对于带有查询字符串的URL,不要使用NSURL initWithScheme:(NSString *)scheme host:(NSString *)host path:(NSString *)path,因为它会向路径中添加更多的转义百分比。

票数 105
EN

Stack Overflow用户

发布于 2010-08-06 20:20:50

代码语言:javascript
复制
NSString *encodedString = [myString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

它不会替换你的内联字符串;它会返回一个新的字符串。该方法以单词"string“开头的事实表明了这一点。根据当前的NSString实例化NSString的新实例是一种方便的方法。

注意--新的字符串将是autorelease'd,所以当你使用完它时,不要对它调用release。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3423545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档