2

我使用NSString stringWithFormat方法来创建一个 URL 字符串。但是现在我在“快速”编辑这个字符串时遇到了问题。

例如,我在服务器上有一个脚本,它处理一些带有参数的请求。

我有一个这样的 URL 字符串:

http://www.domain.com/api/?param1=%@&param2=%@&param3=%@&param4=%@&param5=%@&

但是当我有超过 5、6 个参数时,真的很难修改这个字符串。

任何人都知道如何创建 URL 字符串的最佳方法(我的意思是当我们修改它时)。

4

2 回答 2

6

这是如何以安全方式添加参数的示例。长而可靠。

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
于 2012-08-02T22:15:50.330 回答
4

我专门为你写了这个,很简单:

+ (NSString*) URlStringForBaseURL:(NSString*)baseURL withParams:(NSDictionary*)paramsdictonary{
NSString* url = [baseURL stringByAppendingString:@"?"];
NSUInteger index = 0;
for (NSString* key in [paramsdictonary allKeys]) {
    index++;
    if (index == [paramsdictonary count]) 
        url =  [url stringByAppendingFormat:@"%@=%@",key,[paramsdictonary valueForKey:key]];
    else
        url =  [url stringByAppendingFormat:@"%@=%@&",key,[paramsdictonary valueForKey:key]];
}
return url;
}

您可以使用它(当然,URL 参数的顺序无关紧要):

NSMutableDictionary* params = [NSMutableDictionary dictionary];
[params setValue:@"value1" forKey:@"param1"];
[params setValue:@"value2" forKey:@"param2"];
[params setValue:@"value3" forKey:@"param3"];

NSString* urlStr = [HTMLTextFormat URlStringForBaseURL:@"http://www.domain.com/api/" withParams:params];

NSLog(@"url_: %@",urlStr);
于 2012-08-02T22:48:42.693 回答