Codificando argumentos de string para URLs
Eu criei um método para criar URLs para mim.
- (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;
}
Quando tento construir algo como abaixo, os URLs não são codificados, é claro.
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://other.com", @"url",
@"ABCDEF", @"apiKey", nil];
NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`
O valor retornado éhttp://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF quando deveria serhttp://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF.
Eu preciso codificar a chave e o valor. Eu procurei por algo e encontreiCFURLCreateStringByAddingPercentEscapes estringByAddingPercentEscapesUsingEncoding mas nenhum dos testes que fiz funcionou.
Como eu posso fazer isso?