Note that there are some explanatory texts on larger screens.

plurals
  1. POEncoding string arguments for URLs
    text
    copied!<p>I created a method to build URLs for me.</p> <pre><code>- (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:@"&amp;%@=%@", key, [args objectForKey:key]]]; } } return url; } </code></pre> <p>When I try to build something like below, the URLs aren't encoded, of course.</p> <pre><code>NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys: @"http://other.com", @"url", @"ABCDEF", @"apiKey", nil]; NSLog(@"%@", [self urlFor:@"articles" arguments:args]);` </code></pre> <p>The returned value is <strong><a href="http://api.example.com/articles?version=2.0.1&amp;url=http://other.com&amp;apiKey=ABCDEF" rel="nofollow noreferrer">http://api.example.com/articles?version=2.0.1&amp;url=http://other.com&amp;apiKey=ABCDEF</a></strong> when it should be <strong><a href="http://api.example.com/articles?version=2.0.1&amp;url=http%3A%2F%2Fother.com&amp;apiKey=ABCDEF" rel="nofollow noreferrer">http://api.example.com/articles?version=2.0.1&amp;url=http%3A%2F%2Fother.com&amp;apiKey=ABCDEF</a></strong>.</p> <p>I need to encode both key and value. I searched for something and found <strong>CFURLCreateStringByAddingPercentEscapes</strong> and <strong>stringByAddingPercentEscapesUsingEncoding</strong> but none of the tests I made worked.</p> <p>How can I do it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload