我为我创建了一个构建URL的方法。对URL的字符串参数进行编码
- (NSString *)urlFor:(NSString *)path arguments:(NSDictionary *)args
{
NSString *format = @"http://api.example.com/%@?version=2.0.1";
NSMutableString *url = [NSMutableString stringWithFormat:format, path];
if ([args isKindOfClass:[NSDictionary class]]) {
for (NSString *key in args) {
[url appendString:[NSString stringWithFormat:@"&%@=%@", key, [args objectForKey:key]]];
}
}
return url;
}
当我尝试构建如下所示的内容时,URL当然不会被编码。
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://other.com", @"url",
@"ABCDEF", @"apiKey", nil];
NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`
返回的值是http://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF当它应该是http://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF。
我需要对密钥和值进行编码。我搜索了一些东西,发现CFURLCreateStringByAddingPercentEscapes和stringByAddingPercentEscapesUsingEncoding但我没有做任何测试工作。
我该怎么办?
对不起!我的代码打破了语法高亮,我无法修复它!任何人? – 2009-08-09 00:07:23