Kodowanie argumentów łańcuchowych dla adresów URL
Stworzyłem metodę budowania adresów URL dla mnie.
- (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;
}
Kiedy próbuję zbudować coś takiego jak poniżej, oczywiście adresy URL nie są kodowane.
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://other.com", @"url",
@"ABCDEF", @"apiKey", nil];
NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`
Zwracana wartość tohttp://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF kiedy powinno byćhttp://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF.
Muszę zakodować zarówno klucz, jak i wartość. Szukałem czegoś i znalazłemCFURLCreateStringByAddingPercentEscapes istringByAddingPercentEscapesUsingEncoding ale żaden z testów, które wykonałem, nie działał.
Jak mogę to zrobić?