【发布时间】:2009-08-09 00:04:47
【问题描述】:
我创建了一个为我构建 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 但我所做的测试都没有奏效。
我该怎么做?
【问题讨论】:
-
对不起!我的代码破坏了语法突出显示,我无法修复它!有人吗?
标签: objective-c cocoa