对于Objective-C:
NSString *str = ...; // some URL
NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet];
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
在哪里可以找到NSUTF8StringEncoding的集合?
有六个URL组件和子组件的预定义字符集,它们允许百分比编码。这些字符集传递给 -stringByAddingPercentEncodingWithAllowedCharacters:
。
// Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
@interface NSCharacterSet (NSURLUtilities)
+ (NSCharacterSet *)URLUserAllowedCharacterSet;
+ (NSCharacterSet *)URLPasswordAllowedCharacterSet;
+ (NSCharacterSet *)URLHostAllowedCharacterSet;
+ (NSCharacterSet *)URLPathAllowedCharacterSet;
+ (NSCharacterSet *)URLQueryAllowedCharacterSet;
+ (NSCharacterSet *)URLFragmentAllowedCharacterSet;
@end
弃用消息说(强调我):
请改用stringByAddingPercentEncodingWithAllowedCharacters(_ :),它始终使用建议的UTF-8编码,并且对特定的URL组件或子组件进行编码,因为每个URL组件或子组件对有效字符的使用规则有所不同。
因此,您只需要提供足够NSCharacterSet
的参数即可。幸运的是,对于URL,有一个非常方便的类方法URLHostAllowedCharacterSet
,您可以像这样使用:
NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet];
但是请注意:
此方法旨在对URL组件或子组件字符串(而非整个URL字符串)进行百分比编码。
NSURLComponents
,它可以为您处理百分比编码。