我使用 NSString stringWithFormat
方法创建一个 URL 字符串。但是现在我在“快速”编辑这个字符串时遇到了问题。
例如,我在服务器上有一个脚本可以处理一些带参数的请求。
我有一个这样的 URL 字符串:
http://www.domain.com/api/?param1=%@¶m2=%@¶m3=%@¶m4=%@¶m5=%@&
但是当我有超过 5、6 个参数时,很难修改这个字符串。
任何人都知道如何创建 URL 字符串的最佳方法(我的意思是当我们修改它时)。
最佳答案
这是一个如何以安全的方式添加参数的示例。长但可靠。
NSString* const kBaseURL = @"http://maps.google.com/maps/api/geocode/xml";
NSMutableDictionary *parameterDic = [NSMutableDictionary dictionary];
[parameterDic setObject:@"plaza de la puerta del sol 1, madrid, spain" forKey:@"address"];
[parameterDic setObject:@"false" forKey:@"sensor"];
NSMutableArray *parameters = [NSMutableArray array];
for (__strong NSString *name in parameterDic) {
NSString *value = [parameterDic objectForKey:name];
name = encodeToPercentEscapeString(name);
value = encodeToPercentEscapeString(value);
NSString *queryComponent = [NSString stringWithFormat:@"%@=%@", name, value];
[parameters addObject:queryComponent];
}
NSString *query = [parameters componentsJoinedByString:@"&"];
NSString *urlString = [NSString stringWithFormat:@"%@?%@", kBaseURL, query];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(@"%@",url);
上面的代码调用这个C函数是因为stringByAddingPercentEscapesUsingEncoding不会转换参数名称或参数值中的一些特殊字符。正如 Jesse Rusak 所指出的,请参阅 Proper URL (Percent) Encoding in iOS进行讨论。
// remove CFBridgingRelease and __bridge if your code is not ARC
NSString* encodeToPercentEscapeString(NSString *string) {
return (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef) string,
NULL,
(CFStringRef) @"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
}
这打印
http://maps.google.com/maps/api/geocode/xml?sensor=false&address=plaza%20de%20la%20puerta%20del%20sol%201,%20madrid,%20spain
奖励轨道:如何解构和重建字符串:
NSString *stringUrl = @"http://www.google.com:80/a/b/c;params?m=n&o=p#fragment";
NSURL *url = [NSURL URLWithString:stringUrl];
NSLog(@"%@",stringUrl);
NSLog(@" scheme: %@",[url scheme]);
NSLog(@" host: %@",[url host]);
NSLog(@" port: %@",[url port]);
NSLog(@" path: %@",[url path]);
NSLog(@" relativePath: %@",[url relativePath]);
NSLog(@"parameterString: %@",[url parameterString]);
NSLog(@" query: %@",[url query]);
NSLog(@" fragment: %@",[url fragment]);
NSMutableString *s = [NSMutableString string];
[s appendFormat:@"%@://%@",[url scheme],[url host]];
if ([url port]!=nil){
[s appendFormat:@":%@",[url port]];
}
[s appendFormat:@"%@",[url path]];
if ([url parameterString]!=nil){
[s appendFormat:@";%@",[url parameterString]];
}
if ([url query]!=nil){
[s appendFormat:@"?%@",[url query]];
}
if ([url fragment]!=nil){
[s appendFormat:@"#%@",[url fragment]];
}
NSLog(@"%@",s);
这打印
http://www.google.com:80/a/b/c;params?m=n&o=p#fragment
scheme: http
host: www.google.com
port: 80
path: /a/b/c
relativePath: /a/b/c
parameterString: params
query: m=n&o=p
fragment: fragment
关于ios - 将 url 字符串与 NSString stringWithFormat 一起使用的最佳做法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11786405/