javascript encodeURIComponent等效对象-c

bq9c1y66  于 2023-05-27  发布在  Java
关注(0)|答案(4)|浏览(243)

我在谷歌上搜索这个有点困难。
Objective-C有编码URI组件的等效方法吗?
http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp
这似乎是一个非常常见的用例,但我在Objective-C中找不到任何关于它的文档。
谢谢。

kuarbcqp

kuarbcqp1#

-[NSString stringByAddingPercentEscapesUsingEncoding:]是最简单的方法。

l5tcr1uw

l5tcr1uw2#

当然,你也可以选择这种方法,希望对你有所帮助。

//encode URL string

+(NSString *)URLEncodedString:(NSString *)str
{

    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));

    return encodedString;
}

}

//decode URL string

+(NSString *)URLDecodedString:(NSString *)str
{

  NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

    return decodedString;
}
uplii1fm

uplii1fm3#

现在stringByAddingPercentEscapesUsingEncoding:已弃用。以下是iOS 7+中encodeURIComponent的等效版本:

[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]
bfnvny8b

bfnvny8b4#

使用CFURLCreateStringByAddingPercentEscapesstringByAddingPercentEscapesUsingEncoding并不理想,因为它们是不推荐使用的方法。
戴夫的回答是正确的,但不够明确。
我们想调用stringByAddingPercentEncodingWithAllowedCharacters,但需要选择一个字符集。不管我们的直觉怎么说,NSCharacterSet.URLQueryAllowedCharacterSet实际上不是一个好的选择。它引用URL的整个查询部分,而不仅仅是查询参数的值,因此它也允许像?&这样的字符,这些字符在这里是无效的。您需要的是根据文档手动构建允许的字符集并使用它。encodeURIComponent()允许的字符是:

A–Z a–z 0–9 - _ . ! ~ * ' ( )

这给了我们这个解决方案:

// Note: Using NSCharacterSet.URLQueryAllowedCharacterSet is inappropriate for this purpose.
// It contains the allowed chars for the whole Query part of the URL (including '?' or '&'),
// not just for the values of query parameters (where chars are more restricted).

+ (NSString *)encodeURIComponent:(NSString *)uriComponent {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
    NSString *allowedChars = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "abcdefghijklmnopqrstuvwxyz"
                              "0123456789"
                              "-_.!~*'()";

    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:allowedChars];
    return [uriComponent stringByAddingPercentEncodingWithAllowedCharacters:charSet];
}

+ (NSString *)decodeURIComponent:(NSString *)uriComponent {
    return [uriComponent stringByRemovingPercentEncoding];
}

相关问题