encodeURIComponent equivalent object-c

encodeURIComponent equivalent object-c

本文关键字:object-c equivalent encodeURIComponent      更新时间:2023-09-26

我在谷歌上搜索这个时遇到了麻烦。

Objective-C是否有编码URI组件的等效方法?

http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

这似乎是一个非常常见的用例,但我在 Objective-C 中找不到任何关于它的文档。

谢谢。

-[NSString stringByAddingPercentEscapesUsingEncoding:]

最简单的方法。

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

//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;
}

现在stringByAddingPercentEscapesUsingEncoding:已被弃用。这是相当于encodeURIComponent的iOS 7+:

[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]

使用 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];
}