iOS 7 SDK现在有一个更好的替代选择stringByAddingPercentEscapesUsingEncoding
,它允许您指定要转义除某些允许的字符以外的所有字符。如果您要部分构建URL,那么它会很好地工作:
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类别中的常量也是如此:
[NSCharacterSet URLHostAllowedCharacterSet]
[NSCharacterSet URLUserAllowedCharacterSet]
[NSCharacterSet URLPasswordAllowedCharacterSet]
[NSCharacterSet URLPathAllowedCharacterSet]
[NSCharacterSet URLFragmentAllowedCharacterSet]
[NSCharacterSet URLQueryAllowedCharacterSet]
包括URL的查询部分中允许的所有字符(对于片段而言,该部分以,?
和开头#
,如果有的话),包括,?
和&
或=
字符,用于分隔参数名称和值。对于带有字母数字值的查询参数,这些字符中的任何一个都可能包含在用于构建查询字符串的变量的值中。在这种情况下,查询字符串的每个部分都需要转义,这需要做更多的工作:
NSMutableCharacterSet * URLQueryPartAllowedCharacterSet;
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:@"&+=?"];
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,如回调或重定向:
NSString * escapedCallbackParamValue = [anAlreadyEscapedCallbackURL stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSURL * callbackURL = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"http://ExampleOnly.com/path.ext?callback=%@", escapedCallbackParamValue]];
注意:请勿NSURL initWithScheme:(NSString *)scheme host:(NSString *)host path:(NSString *)path
用于带有查询字符串的URL,因为它将为路径添加更多的转义百分比。